利用HttpModule实现图片验证码.无实用价值,仅实验HttpModule功能使用。
说明:图片生成部分抄自张子阳的Asp.Net架构
using System; using System.Web; using System.Drawing; using System.Drawing.Imaging; using System.Text; namespace MyHttpModule { public class MyHttpModule :IHttpModule { public void Init(HttpApplication app) { app.BeginRequest += new EventHandler(this.App_BeginRequest); //app.EndRequest += new EventHandler(this.App_EndRequest); //app.PreRequestHandlerExecute += new EventHandler(this.App_PreRequest); } public void App_PreRequest(Object obj, EventArgs e) { HttpApplication app = (HttpApplication)obj; HttpContext ctx = app.Context; HttpResponse rsp = ctx.Response; rsp.Write(ctx.CurrentHandler.GetType().FullName); rsp.Write("<br/>"); rsp.Write(ctx.CurrentHandler.ToString()); rsp.Write("<br/>"); rsp.Write(ctx.CurrentHandler.IsReusable); rsp.Write("<br/>"); rsp.Write(ctx.CurrentHandler.GetHashCode()); rsp.Write("<br/>"); rsp.Write("-----华丽的分割线----------"); rsp.Write("<br/>"); rsp.Write(ctx.Handler.GetType().FullName); rsp.Write("<br/>"); rsp.Write(ctx.Handler.ToString()); rsp.Write("<br/>"); rsp.Write(ctx.Handler.IsReusable); rsp.Write("<br/>"); rsp.Write(ctx.CurrentHandler.GetHashCode()); rsp.Write("<br/>"); //ctx.CurrentHandler.ProcessRequest(ctx); //app.CompleteRequest(); } public void App_BeginRequest(Object obj, EventArgs e) { HttpApplication app = (HttpApplication)obj; HttpContext ctx = app.Context; HttpResponse rsp = ctx.Response; //rsp.Write("我来自Application Begin Request"); rsp.ContentType = "image/gif"; 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 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 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(rsp.OutputStream, ImageFormat.Gif); rsp.End(); } public void App_EndRequest(Object obj, EventArgs e) { HttpApplication app = (HttpApplication)obj; HttpContext ctx = app.Context; HttpResponse rsp = ctx.Response; rsp.Write("我来自Application End Request"); } public void Dispose() { } } }