HttpHandler对象实现验证码
验证码
验证码(Captcha)是加强网站安全地必备技术,是重要的验证方法之一
创建Web页面
<body>
<form id="form1" runat="server">
<div>
<img src="images/1.jpg" />
</div>
</form>
</body>
创建Handler类,并实现接口IHttpHandler与IrequiresSessionState
namespace
{
/// <summary>
/// 生成验证码
/// </summary>
public class HttpHandle : IHttpHandler,IRequiresSessionState
{
//生成随机数
private Random RandomSeed = new Random();
public void ProcessRequest(HttpContext context)
{
//定义字符串
string strWord = "23456789QWERTYUIOPASDFGHJKLZXCVBNM";
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;
}
}
}
}
配置Web.config
<configuration>
<system.webServer>
<handlers>
<add verb="*" name="h1" path="images/*" type="WebCode.HttpHandle"/>
</handlers>
</system.webServer>
</configuration>