Loading

ASP.NET验证码生成与识别

   一般验证码页面只输出一个图片而不进行其他业务处理,所以验证码一般放在一般处理程序(httpHandler)页面中,而如果将验证码生成代码放到一般处理程序中,要将生成验证码保存在Session中,这里我们假设保存到session["ValidCode"]中,则需要添加对 System.Web.SessionState 命名空间的引用,并要实现 IHttpHandler和IRequiresSessionState接口,这样才能实现将验证码保存到session中,生成验证码示例代码如下:

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Drawing;
  4 using System.Drawing.Drawing2D;
  5 using System.Text;
  6 using System.Web;
  7 using System.Web.SessionState;
  8 
  9 namespace 验证码的生成与识别
 10 {
 11     /// <summary>
 12     /// 生成验证码
 13     /// </summary>
 14     public class ValidCodeHandler : IHttpHandler,IRequiresSessionState
 15     {
 16 
 17         public void ProcessRequest(HttpContext context)
 18         { 
 19             // 产生5位随机字符
 20             string strValidCode = GetValidCode(5);                                                  
 21 
 22             //如果要使用context.Session,需要添加命名空间System.Web.SessionState   using System.Web.SessionState;  ,然后再继承IRequiresSessionState接口
 23             //将字符串保存到Session中,以便需要时进行验证
 24             context.Session["ValidCode"] = strValidCode;
 25             //定义宽120像素,高30像素的数据定义的图像对象
 26             Bitmap image = new Bitmap(120, 40);
 27             //绘制图片                                                     
 28             Graphics g = Graphics.FromImage(image);                                                 
 29             try
 30             {
 31                 //创建随机数生成器
 32                 Random random = new Random();
 33                 //清除图片背景色                                       
 34                 g.Clear(Color.White);                                                               
 35                 // 随机产生图片的背景噪线
 36                 for (int i = 0; i < 25; i++)                                               
 37                 {
 38                     int x1 = random.Next(image.Width);
 39                     int x2 = random.Next(image.Width);
 40                     int y1 = random.Next(image.Height);
 41                     int y2 = random.Next(image.Height);
 42                     g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
 43                 }
 44                 //设置图片字体风格
 45                 Font font = new System.Drawing.Font("微软雅黑", 20, (System.Drawing.FontStyle.Bold));  
 46                 LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 3, true);//设置画笔类型
 47                 //绘制随机字符
 48                 g.DrawString(strValidCode, font, brush, 5, 2);  
 49                 //绘制图片的前景噪点
 50                 g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);    
 51                 //建立存储区为内存的流
 52                 System.IO.MemoryStream ms = new System.IO.MemoryStream();   
 53                 //将图像对象储存为内存流        
 54                 image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);        
 55                 //清除当前缓冲区流中的所有内容      
 56                 context.Response.ClearContent();                                                    
 57                 //设置输出流的MIME类型
 58                 context.Response.ContentType = "image/png";
 59                 //将内存流写入到输出流                         
 60                 context.Response.BinaryWrite(ms.ToArray());                                         
 61             }
 62             finally
 63             {
 64                 //释放资源
 65                 g.Dispose();
 66                 image.Dispose();
 67             }
 68         }
 69 
 70         /// <summary>
 71         /// 生成随机字符串
 72         /// </summary>
 73         /// <param name="num">随机字符的个数</param>
 74         /// <returns>返回随机产生的字符串</returns>
 75         private string GetValidCode(int num)
 76         {
 77             //定义一个允许的字符组成的字符串
 78             string strRandomCode = "ABCD1EF2GH3IJ4KL5MN6P7QR8ST9UVWXYZ";                                //定义要随机抽取的字符串
 79             //char[] chaStr = strRandomCode.ToCharArray();                                                //第二种方法:将定义的字符串转成字符数组
 80             StringBuilder sbValidCode = new StringBuilder();                                            //定义StringBuilder对象用于存放验证码
 81             //随机数生成器,用于随机产生验证码中字符
 82             Random rnd = new Random();                                                                   //随机函数,随机抽取字符
 83             for (int i = 0; i < num; i++)
 84             {
 85                 //随机获取一个字符
 86                 char a = strRandomCode[rnd.Next(0, strRandomCode.Length)];
 87                 //拼接字符
 88                 sbValidCode.Append(a);
 89             }
 90             return sbValidCode.ToString();
 91         }
 92 
 93 
 94 
 95         public bool IsReusable
 96         {
 97             get
 98             {
 99                 return false;
100             }
101         }
102     }
103 }
生成验证码

  生成验证码之后,就是用户的输入与验证码的对比,刚才我们已经将验证码保存到session中,检查用户输入的验证码是否正确只需将用户输入值与保存到session中的值即【session["ValidCode"].ToString()】(类型转换,session["ValidCode"]转化为string类型)比较即可,我们可以在code页面验证,也可在一般处理程序中验证(更为常用,可利用Ajax技术,提高用户体验),

  code验证示例代码:

1 //判断用户输入验证码与保存在session中验证码是否一致
2  if (txtValidCode.Text.ToUpper() == Session["Code"].ToString().ToUpper())
Code页验证

  一般处理程序示例代码如下:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Web;
 4 using System.Web.SessionState;
 5 
 6 namespace 验证码的生成与识别
 7 {
 8     /// <summary>
 9     /// 验证用户输入验证码是否正确
10     /// </summary>
11     public class Handler1 : IHttpHandler,IRequiresSessionState
12     {
13 
14         public void ProcessRequest(HttpContext context)
15         {
16             context.Response.ContentType = "text/plain";
17             //获取用户输入验证码
18             string strCode = context.Request["txtValidCode"].ToString();
19             //ToUpper(),这里验证码不区分大小写
20             if (strCode.ToUpper() == context.Session["ValidCode"].ToString().ToUpper())
21             {
22                 context.Response.Write("验证码正确!");
23             }
24             else
25             {
26                 context.Response.Write("验证码错误!");
27             }
28         }
29 
30         public bool IsReusable
31         {
32             get
33             {
34                 return false;
35             }
36         }
37     }
38 }
httpHandler验证

 

posted @ 2014-10-22 17:49  WeihanLi  阅读(1006)  评论(0编辑  收藏  举报