asp.net 一般处理程序实现网站验证码

使用VerifyCode.ashx一般处理程序生成验证码,实现如下:

using System;
using System.Drawing;
using System.Web;
using System.Web.SessionState; namespace Zhong.Web
{
/// <summary>
/// VerifyCode 的摘要说明
/// </summary>
public class VerifyCode : IHttpHandler,IRequiresSessionState
{ public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/gif";
string code = GetCode(); //产生6位随机数
context.Session["verifycode"] = code; //保存到Session中
System.Drawing.Bitmap image = new System.Drawing.Bitmap(, );
Graphics g = Graphics.FromImage(image);
try
{
//生成随机生成器
Random random = new Random(); //清空图片背景色
g.Clear(Color.White); // 画图片的背景噪音线
int i;
for (i = ; i < ; i++)
{
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height);
g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
} Font font = new Font("Arial", , (FontStyle.Bold));
System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(, , image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2F, true);
g.DrawString(code, font, brush, , ); //画图片的前景噪音点
g.DrawRectangle(new Pen(Color.Silver), , , image.Width - , image.Height - );
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
context.Response.ClearContent();
context.Response.ContentType = "image/Gif";
context.Response.BinaryWrite(ms.ToArray());
}
finally
{
g.Dispose();
image.Dispose();
}
}
/// <summary>
/// 产生随机数
/// </summary>
/// <param name="length">随机数长度</param>
/// <returns></returns>
private string GetCode(int length)
{
string str = "0123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ";
//char[] letters = str.ToCharArray();
string code = "";
Random random = new Random();
for (int i = ; i < length; i++)
{
code += str.Substring(random.Next(str.Length), );
}
return code;
} public bool IsReusable
{
get
{
return false;
}
}
}
}

特别注意:一般处理程序需要实现IRequiresSessionState接口,目的是使可以读写Session。

上一篇:LeetCode:36. Valid Sudoku,数独是否有效


下一篇:解决tomcat运行报错java.lang.UnsatisfiedLinkError: apache-tomcat-7.0.37\bin\tcnative-1.dll:Can load AMD 64