ASP.NET使用HttpHandler对象实现验证码(完整版)

ASP.NET使用HttpHandler对象实现验证码(完整版)

在这里插入图片描述

登录页面的验证码如何实现?

  1. 添加一般处理程序VerificationCode,并实现接口IHttpHandler,并继承IRequiresSessionState接口。

  2. 实现代码

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.SessionState;

namespace zuoye
{
    /// <summary>
    /// 生成验证码
    /// </summary>
    public class Validatecodehandler : IHttpHandler,IRequiresSessionState
    {
        //生成随机数
        private Random RandomSeed = new Random();
        
        public void ProcessRequest(HttpContext context)
        {
            //定义字符串
            string strWord = "ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz1234567890";
            string NumStr = null;
            //循环生成五个字符
            for (int i = 0; i < 5; i++)
            {
                NumStr += strWord[RandomSeed.Next(0, strWord.Length)];
            }
            //将生成的验证码存入session 中
            context.Session["Code"] = NumStr;
            //调用画图方法
            CreateImages(context, NumStr);

        }
        //定义画图验证码方法
        private void CreateImages(HttpContext context,string CheckCode)
        {
            //定义画布宽度
            int iwidth = (int)(CheckCode.Length * 13);
            Image image = new Bitmap(iwidth, 22);
            //生成图片
            Graphics g = Graphics.FromImage(image);
            //填充白背景
            g.Clear(Color.White);
            //定义颜色
            Color[] c = { Color.Black,Color.DarkBlue,Color.Orange,Color.Purple, Color.Red, Color.Green, Color.Gray, Color.Yellow };
            //定义字体
            string[] font = { "Verdana","Microsoft Sans Serif","宋体","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, System.Drawing.FontStyle.Bold);
                //刷颜色
                Brush b = new System.Drawing.SolidBrush(c[cindex]);
                //相邻的两个字符高低不同
                int ii = 4;
                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();
            //保存Jpeg文件
            image.Save(ms, System.Drawing.Imaging.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;
            }
        }
    }
}

3、前端实现代码

<asp:Label ID="Label3" runat="server" Text="验证码"></asp:Label>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
//点击实现刷新效果
<img src="Validatecodehandler.ashx?id=1" onclick="this.src=this.src+1" />

4、后端取出session与文本框判断即可

string yanzheng = TextBox3.Text;
string yanz = Session["Code"].ToString();
if (yanz==yanzheng)
    {
    	//执行操作
    }

在这里插入图片描述
感谢大佬指正 小Monkey
如果你觉得有用的话,就留个赞吧!蟹蟹

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

猴麦麦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值