MVC(C#)生成和检测图片验证码,支持多页面不同验证码

来源:互联网 发布:淘宝出售假冒商品2次 编辑:程序博客网 时间:2024/05/02 01:30

文章来源:http://blog.csdn.net/wipeouter/article/details/6927734

一、验证码描述类

 

[csharp] view plaincopy
  1. using System;  
  2.   
  3. /// <summary>  
  4. /// 验证码描述  
  5. /// </summary>  
  6. public class ValidateImage  
  7. {  
  8.     public Guid Key { getset; }  
  9.     public string Value { getset; }  
  10. }  


二、生成验证码图片

[csharp] view plaincopy
  1. #region 验证码  
  2.         /// <summary>  
  3.         /// 用于前台调用,key为调用网址生成  
  4.         /// </summary>  
  5.         /// <param name="key"></param>  
  6.         /// <returns></returns>  
  7.         public ActionResult ValidateImgShow(Guid key)  
  8.         {  
  9.             ViewData["Key"] = key;  
  10.             return View();  
  11.         }  
  12.         /// <summary>  
  13.         /// 用于生成验证码图片  
  14.         /// </summary>  
  15.         /// <param name="key"></param>  
  16.         public void ValidateImg(Guid key)  
  17.         {  
  18.   
  19.             Response.ContentEncoding = System.Text.Encoding.UTF8;  
  20.   
  21.             Bitmap imgOutput = new Bitmap(100, 24, PixelFormat.Format24bppRgb);  
  22.             Graphics g = System.Drawing.Graphics.FromImage(imgOutput);  
  23.             g.Clear(Color.Green);  
  24.             g.SmoothingMode = SmoothingMode.AntiAlias;  
  25.   
  26.   
  27.             //为了支持每个用户不同页显示不同的验证码,session里存储一个ValidateImage序列,每列对应一个key和value  
  28.             List<ValidateImage> sessions;  
  29.             ValidateImage img = new ValidateImage()  
  30.             {  
  31.                 Key = key,  
  32.                 Value = getCode()  
  33.             };  
  34.             if (Session["validateCode"] == null)  
  35.             {  
  36.                 sessions = new List<ValidateImage>();  
  37.                 sessions.Add(img);  
  38.             }  
  39.             else  
  40.             {  
  41.                 sessions = (List<ValidateImage>)Session["validateCode"];  
  42.                 bool isExist = false;  
  43.                 for (int i = 0; i < sessions.Count; i++)  
  44.                 {  
  45.                     //如果已经存在此key的验证码seesion,则修改  
  46.                     if (sessions[i].Key == key)  
  47.                     {  
  48.                         isExist = true;  
  49.                         sessions[i] = img;  
  50.                     }  
  51.                 }  
  52.                 if (!isExist)  
  53.                 {  
  54.                     //每个用户同时最多支持30个验证码  
  55.                     if (sessions.Count > 30)  
  56.                     {  
  57.                         sessions.RemoveAt(0);//删除第一个  
  58.                     }  
  59.                     sessions.Add(img);  
  60.                 }  
  61.             }  
  62.             Session["validateCode"] = sessions;  
  63.   
  64.   
  65.             string tmpData = img.Value;  
  66.             g.DrawString(tmpData, new Font("黑体", 13, FontStyle.Bold), new SolidBrush(Color.White), new PointF(10, 1));  
  67.             g.FillRectangle(new LinearGradientBrush(new Point(0, 0), new Point(99, 21), Color.FromArgb(0, 0, 0, 0), Color.FromArgb(215, 215, 215, 215)), 0, 0, 99, 21);  
  68.             imgOutput.Save(Response.OutputStream, ImageFormat.Jpeg);  
  69.             g.Dispose();  
  70.             imgOutput.Dispose();  
  71.             Response.End();  
  72.         }  
  73.         /// <summary>  
  74.         /// 随机生成验证码  
  75.         /// </summary>  
  76.         /// <returns></returns>  
  77.         private string getCode()  
  78.         {  
  79.   
  80.             string vchar = "1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,U,V,W,X,Y,Z";  
  81.             string[] vcarray = vchar.Split(new char[] { ',' });  
  82.             string vnum = "";  
  83.             int iSeed = 4;  
  84.             Random ra = new Random();  
  85.             for (byte i = 1; i < 5; i++)  
  86.             {  
  87.                 iSeed = ra.Next(0, 32);  
  88.                 vnum += vcarray[iSeed];  
  89.             }  
  90.             return vnum;  
  91.         }  
  92.         #endregion  


三、获取当前页对应验证码的值

[csharp] view plaincopy
  1. /// <summary>  
  2.         /// 获取某页(以key为区别)当前图片验证码,如超时,为null  
  3.         /// </summary>  
  4.         /// <returns></returns>  
  5.         public static string GetValidateCode(HttpContextBase context, Guid codeKey)  
  6.         {  
  7.             if (context.Session["validateCode"] == null)  
  8.                 return null;  
  9.             //return Bzh.DataConvert.getStringFromObject(context.Session["validateCode"]);  
  10.             List<ValidateImage> imgs = (List<ValidateImage>)context.Session["validateCode"];  
  11.             string code = "";  
  12.             for (int i = 0; i < imgs.Count; i++)  
  13.             {  
  14.                 if (imgs[i].Key == codeKey)  
  15.                     code = imgs[i].Value;  
  16.             }  
  17.             return code;  
  18.         }  


四、客户端显示验证码

[html] view plaincopy
  1. <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>  
  2.   
  3. <html xmlns="http://www.w3.org/1999/xhtml">  
  4. <head>  
  5.     <title>无标题页</title>  
  6.     <% Guid key = (Guid)ViewData["Key"]; %>  
  7.     <%Response.Write("<script>var _key='" + key.ToString() + "';</script>"); %>  
  8.   
  9.     <script>  
  10.         function refresh_() {  
  11.             var d = new Date();  
  12.             document.getElementById("dimg").src = "/Home/Validateimg?key=" + _key + "&d=" + d.getTime().toString();  
  13.         }  
  14.     </script>  
  15.   
  16. </head>  
  17. <body style="padding: 0; margin: 0;">  
  18.     <a href="#" onclick="refresh_();return false;">  
  19.         <img src="/Home/Validateimg?key=<%=key.ToString() %>" id="dimg" alt="点击重新加载" style="border: 0;" /></a>  
  20. </body>  
  21. </html>  


五、从iframe调用显示

[html] view plaincopy
  1. <td>  
  2.                     <%  
  3.                         Guid valImgKey = Guid.NewGuid();  
  4.                         Response.Write("<script>var _key='" + valImgKey.ToString() + "';</script>");  
  5.                          %>  
  6.                     <iframe src="/Home/ValidateImgShow?key=<%=valImgKey.ToString() %>" style="width: 120px; height: 24px; overflow: hidden"  
  7.                         scrolling="no" frameborder="0"></iframe>  
  8.                 </td>  

对于获取验证码的那段,可以用Linq简化代码:
[csharp] view plaincopy
  1. /// <summary>  
  2.         /// 获取某页(以key为区别)当前图片验证码,如超时,为null  
  3.         /// </summary>  
  4.         /// <returns></returns>  
  5.         public static string GetValidateCode(HttpContextBase context, Guid codeKey)  
  6.         {  
  7.             if (context.Session["validateCode"] == null)  
  8.                 return null;  
  9.             List<ValidateImage> imgs = (List<ValidateImage>)context.Session["validateCode"];  
  10.             string code = "";  
  11.             var query = from t in imgs where t.Key == codeKey select t.Value;  
  12.             foreach (string v in query)  
  13.             {  
  14.                 code = v;  
  15.             }  
  16.             return code;  
  17.         }  

0 0
原创粉丝点击