通过IhttpHandler实现图片验证码
Step.1 打开Vs2005,“添加新项”,“一般处理程序”。新建文件后,VS会自动在文件中添加如下的代码:
<%@ WebHandler Language="C#" Class="Handler" %> using System; using System.Web; public class Handler : IHttpHandler { public void ProcessRequest (HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Write("Hello World"); } public bool IsReusable { get { return false; } } } Step.2 将代码改写成如下所示: <%@ WebHandler Language="C#" Class="Handler" %> using System; using System.Drawing; using System.Drawing.Imaging; using System.Text; using System.Web; using System.Web.SessionState; public class Handler : IHttpHandler, IRequiresSessionState { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "image/gif"; //建立Bitmap对象,绘图 Bitmap basemap = new Bitmap(200, 60); Graphics graph = Graphics.FromImage(basemap); graph.FillRectangle(new SolidBrush(Color.White), 0, 0, 200, 60); Font font = new Font(FontFamily.GenericSerif, 48, FontStyle.Bold, GraphicsUnit.Pixel); Random r = new Random(); string letters = "ABCDEFGHIJKLMNPQRSTUVWXYZ"; string letter; StringBuilder s = new StringBuilder(); //添加随机的五个字母 for (int x = 0; x < 5; x++) { letter = letters.Substring(r.Next(0, letters.Length - 1), 1); s.Append(letter); graph.DrawString(letter, font, new SolidBrush(Color.Black), x * 38, r.Next(0, 15)); } //混淆背景 Pen linePen = new Pen(new SolidBrush(Color.Black), 2); for (int x = 0; x < 6; x++) graph.DrawLine(linePen, new Point(r.Next(0, 199), r.Next(0, 59)), new Point(r.Next(0, 199), r.Next(0, 59))); //将图片保存到输出流中 basemap.Save(context.Response.OutputStream, ImageFormat.Gif); context.Session["CheckCode"] = s.ToString(); //如果没有实现IRequiresSessionState,则这里会出错,也无法生成图片 context.Response.End(); } public bool IsReusable { get { return true; } } } 需要特别注意的是,Handler类不仅需要实现 IHttpHandler接口(这个显然),为了在这个Handler类中使用SessionState,还需要实现 IRequiresSessionState接口,对于这个接口,MSDN的解释是这样的:Specifies that the target HTTP handler requires read and write access to session-state values. This is a marker interface and has no methods.(翻译过来是:指定当前Http Handler需要对SessionState值的读写访问权。这是一个标记接口,没有任何方法)。 而实际上,IRequiresSessionState的接口定义是这样的: public interface IRequiresSessionState{} 可见,这个接口没有任何需要实现的方法或属性,大家只要记得:如果想在HttpHandler中使用SessionState,必须实现这个接口,实际上也就是在类的标头将这个接口加进去。 Step.3 新建一个ImageCode.aspx页面,在HTML代码中写下: <img src="Handler.ashx" alt="图片验证码" /> OK,在浏览器中打开ImageCode.aspx |