<%@ WebHandler Language="C#" Class="ValidateCode" Debug="true" %>
using System;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web.SessionState;//一般处理程序中如果要使用Session必须实现此命名空间里的接口
/// <summary>
/// 验证码
/// </summary>
public class ValidateCode : IHttpHandler,IRequiresSessionState{
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "image/jpeg";
string vCode = MakeRandomNum();
context.Session["vcode"] = vCode;
//创建验证码图片对象
using (Bitmap img = new Bitmap(80, 30))
{
using (Graphics g = Graphics.FromImage(img))
{
g.DrawString(vCode, new Font("微软雅黑", 16), Brushes.White, 5, 2);
img.Save(context.Response.OutputStream, ImageFormat.Jpeg);
}
}
}
/// <summary>
/// 生成随机验证码
/// </summary>
/// <returns></returns>
public string MakeRandomNum()
{
int codelength = 4;
int resNum=0;
string RandomCode = string.Empty;
Random r = new Random();
for (int i = 0; i < codelength; i++)
{
resNum = r.Next();
//字符从0~9,A~Z中随机产生,对应的Ascii码分别为48-57,65-90
resNum = resNum % 36;
if (resNum < 10)
{
resNum += 48;
}
else
{
resNum += 55;
}
RandomCode += ((char)resNum).ToString();
}
return RandomCode;
}
public bool IsReusable
{
get {
return false;
}
}
}