HttpHandler对象实现验证码

以用户登录为案例,在登录界面填写账号、密码以外,还需要填写验证码,防止暴力破解密码。

  1. 创建一个网站,并且在网站中添加HttpHandler类,继承IHttpHandler与IRequiresSessionState接口,编写相关代码,代码如下:

注:需添加引用,如下

using System.Drawing;
using System.IO;
using System.Web.SessionState;
using System.Drawing.Imaging;
public class VerificationCode : IHttpHandler, IRequiresSessionState
    {
        //随机数生成
        private Random RandomSeed = new Random();
        public void ProcessRequest(HttpContext context)
        {
            //供验证码使用的字符
            string strWord = "23456789QWERTYUPASDFGHKXCVBNM";
            string NumStr = null;
            for (int i = 0; i < 5; i++)
            {
                NumStr += strWord[RandomSeed.Next(0, strWord.Length)];
            }
            //将验证码保存到Session
            context.Session["vcode"] = NumStr.ToLower();
            CreateImages(context, NumStr);
        }
        public int ii = 4;
        private void CreateImages(HttpContext context, string checkCode)
        {
            int iwidth = (int)(checkCode.Length * 13);
            Bitmap image = new Bitmap(iwidth, 22);
            Graphics g = Graphics.FromImage(image);
            g.Clear(Color.White);
            //定义颜色
            Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
            //定义字体
            string[] font = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };
            Random rand = new Random();
            //随机输出噪点
            for (int i = 0; i < 50; i++)
            {
                int x = rand.Next(image.Width);
                int y = rand.Next(image.Height);
                g.DrawRectangle(new Pen(Color.LightGray, 0), x, y, 1, 1);
            }
            //输出不同字体和颜色的验证码字符
            for (int i = 0; i < checkCode.Length; i++)
            {
                int cindex = rand.Next(7);
                int findex = rand.Next(5);
                Font f = new Font(font[findex], 10, FontStyle.Bold);
                Brush b = new SolidBrush(c[cindex]);
                if ((i + 1) % 2 == 0)
                {
                    ii = 2;
                }
                g.DrawString(checkCode.Substring(i, 1), f, b, 2 + (i * 12), ii);
            }
            //画一个边框
            g.DrawRectangle(new Pen(ColorTranslator.FromHtml("#CCCCCC"), 0), 0, 0, image.Width - 1, image.Height - 1);
            //输出到浏览器
            MemoryStream ms = new MemoryStream();
            image.Save(ms, ImageFormat.Jpeg);
            context.Response.ClearContent();
            context.Response.ContentType = "image/gif";
            context.Response.BinaryWrite(ms.ToArray());
            g.Dispose();
            image.Dispose();
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
  1. 添加一个Web窗体,使用验证码实现登录验证功能。页面部分代码如下:
<body>
    <form id="form1" runat="server">
        <div>
            <table style="width: 100%;">
                <tr>
                    <td>账号:</td>
                    <td>
                        <asp:TextBox ID="txtAccount" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>密码:</td>
                    <td>
                        <asp:TextBox ID="txtPwd" runat="server" TextMode="Password"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>验证码:</td>
                    <td>
                        <asp:TextBox ID="txtCode" runat="server"></asp:TextBox>
                        <asp:Image ID="Image1" runat="server" ImageUrl="~/VerificationCode.ashx" />
                        <asp:LinkButton ID="LinkButton1" runat="server">刷新</asp:LinkButton>
                    </td>
                </tr>
            </table>
            <asp:Button ID="btnSubmit" runat="server" Text="提交" Style="margin-left: 50%; margin-top: 2%" OnClick="btnSubmit_Click" />
            <asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
        </div>
    </form>
</body>
  1. 后台部分代码如下:
 public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string account = txtAccount.Text;
            string password = txtPwd.Text;
            string code = txtCode.Text;
            if (Session["vcode"].ToString()==code.ToLower())
            {
                if (account=="admin"&&password=="123456")
                {
                    Response.Redirect("Index.aspx");
                }
                else
                {
                    lblMessage.Text = "账号或密码不正确!";
                }
            }
            else
            {
                lblMessage.Text = "验证码不正确!";
            }
        }
    }
  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值