ASP.NET使用HttpHandler对象实现验证码(完整版)
登录页面的验证码如何实现?
-
添加一般处理程序VerificationCode,并实现接口IHttpHandler,并继承IRequiresSessionState接口。
-
实现代码
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
如果你觉得有用的话,就留个赞吧!蟹蟹