首页 > Web开发 > 详细

WebForm 验证码

时间:2015-07-20 23:20:25      阅读:404      评论:0      收藏:0      [点我收藏+]

添加一般处理程序

<%@ WebHandler Language="C#" Class="yanzheng" %>

using System;
using System.Web;
using System.Web.SessionState;//IRequiresSessionState的命名空间
using System.Drawing;

public class yanzheng : IHttpHandler, IRequiresSessionState{
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "image/jpeg";//要输出的类型

        Bitmap img = new Bitmap(50,20);//空白图,指定大小
        Graphics gr = Graphics.FromImage(img);//往哪个图上绘制
        Font font = new Font("宋体",12,FontStyle.Bold);//字体样式
        SolidBrush brush = new SolidBrush(Color.White);//设置画笔
        gr.FillRectangle(brush,0,0,50,20);//设置画笔绘制图形的形状
        brush.Color = Color.Red;//绘制图形的颜色


        string s = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";//随即字符数据源
        string str = "";
        Random r = new Random();
        for (int i = 0; i < 4; i++)
        {
            int start = r.Next(62);
            str += s.Substring(start,1).ToString();//取随机数,截取一位,组成4位验证码
        }
        context.Session["yanzheng"] = str;//会话中保存
        gr.DrawString(str,font,brush,0,0);//绘制图形
        //保存图片,通过Response响应流保存
        img.Save(context.Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

界面

<body>
    <form id="form1" runat="server" method="get">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        
        <br />
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:TextBox ID="txtcode" runat="server"></asp:TextBox>
                <asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="yanzheng.ashx" OnClick="ImageButton1_Click" />
        <br />
                <asp:Button ID="btn_checkCode" runat="server" OnClick="btn_checkCode_Click" Text="验证" />
                <br />
                <asp:Label ID="Label1" runat="server"></asp:Label>
            </ContentTemplate>
        </asp:UpdatePanel>
              
    </div>
    </form>
</body>
 protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        ImageButton1.ImageUrl = "yanzheng.ashx?id="+new Random().Next(100);
    }
    protected void btn_checkCode_Click(object sender, EventArgs e)
    {
        string s1 = txtcode.Text.ToUpper();
        string s2 = Session["yanzheng"].ToString().ToUpper();
        if (s1==s2)
        {
            Label1.Text = "验证成功";
        }
        else
        {
            Response.Write("<script>alert(‘验证失败‘)</script>");
        }
    }

技术分享

WebForm 验证码

原文:http://www.cnblogs.com/happinesshappy/p/4662929.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!