首页 > 代码库 > 【2017-6-9】WebForm 随机验证码制作

【2017-6-9】WebForm 随机验证码制作

前台代码

<body>
    <form id="form1" runat="server">
        <div>
            <br />
            <br />
            <%--用户输入的文本框--%>
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <%--验证码图片--%>
            <img id="yzm1" src=http://www.mamicode.com/"YZM.aspx" /><br />
            <%--验证按钮--%>
            <asp:Button ID="Button1" runat="server" Text="验证" />

            <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><br />
            <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
        </div>
    </form>
</body>
</html>
<script type="text/javascript">
    //JS代码是点击图片就刷新验证码
    var a = 0;
    document.getElementById("yzm1").onclick = function () {
        this.src = http://www.mamicode.com/"yzm.aspx?a=" + a;
        a++;
    }



</script>

 

 

后台代码

protected void Page_Load(object sender, EventArgs e)
    {
        Button1.Click += Button1_Click;
    }

    void Button1_Click(object sender, EventArgs e)
    {
        Label2.Text = Session["YZM"].ToString();
        if (TextBox1.Text == Session["YZM"].ToString())
            Label1.Text = "正确!!!";
        else
            Label1.Text = "错误!!!!!!!";
    }

 

 

 

验证码要单独放到一个页面中

验证码后台代码

protected void Page_Load(object sender, EventArgs e)
    {
        //创建一个颜色集
        List<Color> clist = new List<Color>();
        clist.Add(Color.Red);
        clist.Add(Color.Firebrick);
        clist.Add(Color.LawnGreen);
        clist.Add(Color.Goldenrod);
        clist.Add(Color.Cyan);
        clist.Add(Color.DarkSlateBlue);
        clist.Add(Color.Indigo);
        //创建一个随机变量
        Random r = new Random();
        string s = "";
        //添加随机数
        string all = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmeopqrstuvwxyz0123456789";
        //产生四个随机数
        for (int i = 0; i < 4; i++)
        {
            s += all.Substring(r.Next(0, all.Length), 1);
        }

        Session["YZM"] = s;
        //放置验证码的图片
        Bitmap img = new Bitmap(120, 60);

        Graphics g2 = Graphics.FromImage(img);
        //随机背景色
        Brush b2 = new SolidBrush(clist[r.Next(0, clist.Count)]);
        g2.FillRectangle(b2, 0, 0, 120, 60);

        Graphics g = Graphics.FromImage(img);
        Font f = new Font("微软雅黑", 30);
        Brush b = new SolidBrush(Color.Red);

        g.DrawString(s, f, b, new PointF(0, 0));


        //绘制线条,对验证码进行遮罩
        for (int i = 0; i < 8; i++)
        {
            Graphics g3 = Graphics.FromImage(img);
            Pen p3 = new Pen(new SolidBrush(clist[r.Next(0, clist.Count)]), r.Next(2, 5));
            g3.DrawLine(p3, new Point(r.Next(0, 120), r.Next(0, 60)), new Point(r.Next(0, 120), r.Next(0, 60)));
        }



        img.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png);



    }

 

【2017-6-9】WebForm 随机验证码制作