首页 > 技术文章 > ASP.NET MVC生成安全验证码

doctorJoe 2015-04-29 09:50 原文

html部分:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Document</title>
 6 </head>
 7 <body>
 8     <table>
 9         <tr>
10             <td><img id="validImg" src="/Login/CheckCode?ID=1" alt="点我刷新" onclick="changeValidCode()"></td>
11             <td><a href="#" onclick="changeValidCode()">点我刷新</a></td>
12         </tr>
13     </table>
14 
15 
16     <script >
17     $(function(){
18         function changeValidCode(){
19             var code=$("#validImg").attr('src');
20              $("#validImg").attr("src", code + "1");
21         }
22     })
23     </script>
24 </body>
25 </html>

asp.net mvc返回文件地址:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.Mvc;
 6 
 7 namespace MyDemo.Controllers
 8 {
 9     public class LoginController : Controller
10     {
11 
12 
13 
14         /// <summary>
15         /// 用户登录验证码
16         /// </summary>
17         /// <returns></returns>
18         public ActionResult CheckCode()
19         {
20 
21             ValidateCode vCode = new ValidateCode();
22             string code = vCode.CreateValidateCode(5);
23             Session["SysValidateCode"] = code;
24             byte[] bytes = vCode.CreateValidateGraphic(code);
25             return File(bytes, @"image/jpeg");
26         }
27 
28     }
29 }

验证码生成类:

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Drawing;
  4 using System.Drawing.Drawing2D;
  5 using System.Drawing.Imaging;
  6 using System.IO;
  7 using System.Linq;
  8 using System.Text;
  9 
 10 namespace MyDemo.Model
 11 {
 12     /// <summary>
 13     /// 生成验证码的类
 14     /// </summary>
 15     public class ValidateCode
 16     {
 17         public ValidateCode()
 18         {
 19         }
 20         /// <summary>
 21         /// 验证码的最大长度
 22         /// </summary>
 23         public int MaxLength
 24         {
 25             get { return 10; }
 26         }
 27         /// <summary>
 28         /// 验证码的最小长度
 29         /// </summary>
 30         public int MinLength
 31         {
 32             get { return 1; }
 33         }
 34         /// <summary>
 35         /// 生成验证码
 36         /// </summary>
 37         /// <param name="length">指定验证码的长度</param>
 38         /// <returns></returns>
 39         public string CreateValidateCode(int length)
 40         {
 41             int[] randMembers = new int[length];
 42             int[] validateNums = new int[length];
 43             string validateNumberStr = "";
 44             //生成起始序列值
 45             int seekSeek = unchecked((int)DateTime.Now.Ticks);
 46             Random seekRand = new Random(seekSeek);
 47             int beginSeek = (int)seekRand.Next(0, Int32.MaxValue - length * 10000);
 48             int[] seeks = new int[length];
 49             for (int i = 0; i < length; i++)
 50             {
 51                 beginSeek += 10000;
 52                 seeks[i] = beginSeek;
 53             }
 54             //生成随机数字
 55             for (int i = 0; i < length; i++)
 56             {
 57                 Random rand = new Random(seeks[i]);
 58                 int pownum = 1 * (int)Math.Pow(10, length);
 59                 randMembers[i] = rand.Next(pownum, Int32.MaxValue);
 60             }
 61             //抽取随机数字
 62             for (int i = 0; i < length; i++)
 63             {
 64                 string numStr = randMembers[i].ToString();
 65                 int numLength = numStr.Length;
 66                 Random rand = new Random();
 67                 int numPosition = rand.Next(0, numLength - 1);
 68                 validateNums[i] = Int32.Parse(numStr.Substring(numPosition, 1));
 69             }
 70             //生成验证码
 71             for (int i = 0; i < length; i++)
 72             {
 73                 validateNumberStr += validateNums[i].ToString();
 74             }
 75             return validateNumberStr;
 76         }
 77 
 78         /// <summary>
 79         /// 创建验证码的图片
 80         /// </summary>
 81         /// <param name="containsPage">要输出到的page对象</param>
 82         /// <param name="validateNum">验证码</param>
 83         public byte[] CreateValidateGraphic(string validateCode)
 84         {
 85             Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 16.0), 40);
 86             Graphics g = Graphics.FromImage(image);
 87             try
 88             {
 89                 //生成随机生成器
 90                 Random random = new Random();
 91                 //清空图片背景色
 92                 g.Clear(Color.White);
 93                 //画图片的干扰线
 94                 for (int i = 0; i < 25; i++)
 95                 {
 96                     int x1 = random.Next(image.Width);
 97                     int x2 = random.Next(image.Width);
 98                     int y1 = random.Next(image.Height);
 99                     int y2 = random.Next(image.Height);
100                     g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
101                 }
102                 Font font = new Font("Arial", 16, (FontStyle.Bold | FontStyle.Italic));
103                 LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),
104                  Color.Blue, Color.DarkRed, 1.2f, true);
105                 g.DrawString(validateCode, font, brush, 3, 2);
106                 //画图片的前景干扰点
107                 for (int i = 0; i < 100; i++)
108                 {
109                     int x = random.Next(image.Width);
110                     int y = random.Next(image.Height);
111                     image.SetPixel(x, y, Color.FromArgb(random.Next()));
112                 }
113                 //画图片的边框线
114                 g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
115                 //保存图片数据
116                 MemoryStream stream = new MemoryStream();
117                 image.Save(stream, ImageFormat.Jpeg);
118                 //输出图片流
119                 return stream.ToArray();
120             }
121             finally
122             {
123                 g.Dispose();
124                 image.Dispose();
125             }
126         }
127         /// <summary>
128         /// 得到验证码图片的长度
129         /// </summary>
130         /// <param name="validateNumLength">验证码的长度</param>
131         /// <returns></returns>
132         public static int GetImageWidth(int validateNumLength)
133         {
134             return (int)(validateNumLength * 16.0);
135         }
136         /// <summary>
137         /// 得到验证码的高度
138         /// </summary>
139         /// <returns></returns>
140         public static double GetImageHeight()
141         {
142             return 40;
143         }
144     }
145 }

 

推荐阅读