asp.net 一般处理程序实现网站验证码
2017-07-09 23:37
579 查看
使用VerifyCode.ashx一般处理程序生成验证码,实现如下:
View Code
特别注意:一般处理程序需要实现IRequiresSessionState接口,目的是使可以读写Session。
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); //产生6位随机数 context.Session["verifycode"] = code; //保存到Session中 System.Drawing.Bitmap image = new System.Drawing.Bitmap(70, 22); Graphics g = Graphics.FromImage(image); try { //生成随机生成器 Random random = new Random(); //清空图片背景色 g.Clear(Color.White); // 画图片的背景噪音线 int i; for (i = 0; i < 25; 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", 12, (FontStyle.Bold)); System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2F, true); g.DrawString(code, font, brush, 2, 2); //画图片的前景噪音点 g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); 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 = 0; i < length; i++) { code += str.Substring(random.Next(str.Length), 1); } return code; } public bool IsReusable { get { return false; } } } }
View Code
特别注意:一般处理程序需要实现IRequiresSessionState接口,目的是使可以读写Session。
相关文章推荐
- asp.net一般处理程序实现验证码功能
- asp.net实现页面的一般处理程序(CGI)学习笔记
- asp.net实现页面的一般处理程序(CGI)学习笔记
- 用asp.net的一般处理程序写验证码
- ASP.NET使用一般处理程序生成验证码
- ASP.NET知识总结(一般处理程序动态处理图片(验证码、水印、缩略图))
- asp.net ashx一般处理程序实现async await异步操作
- IIS网站或系统验证码不显示问题——"使用了托管的处理程序,但是未安装或未完整安装 ASP.NET"
- IIS网站或系统验证码不显示问题——"使用了托管的处理程序,但是未安装或未完整安装 ASP.NET"
- asp.net 使用一般处理程序和ajax post实现登录以及记住密码
- asp.net的验证码插件及方法、ashx验证码一般处理程序
- (转)Asp.Net 用Jquery和一般处理程序实现无刷新上传大文件
- asp.net用一般处理程序做的验证码
- 使用ASP.NET一般处理程序或WebService返回JSON的实现代码
- asp.net一般处理程序(.ashx)动态生成验证码案例。
- IIS网站或系统验证码不显示问题——"使用了托管的处理程序,但是未安装或未完整安装 ASP.NET"
- 使用ASP.NET一般处理程序或WebService返回JSON的实现代码
- asp.net中使用一般处理程序生成验证码
- IIS网站或系统验证码不显示问题——"使用了托管的处理程序,但是未安装或未完整安装 ASP.NET"