Asp.net mvc生成验证码

1.生成验证码类

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.Web.Mvc;
  6 using System.IO;
  7 using System.Drawing;
  8 using System.Web;
  9 
 10 
 11 namespace SimpleNews.FrontEnd
 12 {
 13     public class ToolController : MyControllerBase
 14     {
 15         /// <summary>
 16         /// 生成验证码字符串
 17         /// </summary>
 18         /// <param name="codeLen">验证码字符长度</param>
 19         /// <returns>返回验证码字符串</returns>
 20         private static string MakeCode(int codeLen)
 21         {
 22             if (codeLen < 1)
 23             {
 24                 return string.Empty;
 25             }
 26             int number;
 27             StringBuilder sbCheckCode = new StringBuilder();
 28             Random random = new Random();
 29 
 30             for (int index = 0; index < codeLen; index++)
 31             {
 32                 number = random.Next();
 33 
 34                 if (number % 2 == 0)
 35                 {
 36                     sbCheckCode.Append((char)('0' + (char)(number % 10))); //生成数字
 37                 }
 38                 else
 39                 {
 40                     sbCheckCode.Append((char)('A' + (char)(number % 26))); //生成字母
 41                 }
 42             }
 43             return sbCheckCode.ToString();
 44         }
 45 
 46         ///<summary>
 47         /// 获取验证码图片流
 48         /// </summary>
 49         /// <param name="checkCode">验证码字符串</param>
 50         /// <returns>返回验证码图片流</returns>
 51         public static MemoryStream CreateCodeImg(string checkCode)
 52         {
 53             if (string.IsNullOrEmpty(checkCode))
 54             {
 55                 return null;
 56             }
 57             Bitmap image = new Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);
 58             Graphics graphic = Graphics.FromImage(image);
 59             try
 60             {
 61                 Random random = new Random();
 62                 graphic.Clear(Color.White);
 63                 int x1 = 0, y1 = 0, x2 = 0, y2 = 0;
 64                 for (int index = 0; index < 25; index++)
 65                 {
 66                     x1 = random.Next(image.Width);
 67                     x2 = random.Next(image.Width);
 68                     y1 = random.Next(image.Height);
 69                     y2 = random.Next(image.Height);
 70 
 71                     graphic.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
 72                 }
 73                 Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));
 74                 System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Red, Color.DarkRed, 1.2f, true);
 75                 graphic.DrawString(checkCode, font, brush, 2, 2);
 76 
 77                 int x = 0;
 78                 int y = 0;
 79 
 80                 //画图片的前景噪音点
 81                 for (int i = 0; i < 100; i++)
 82                 {
 83                     x = random.Next(image.Width);
 84                     y = random.Next(image.Height);
 85 
 86                     image.SetPixel(x, y, Color.FromArgb(random.Next()));
 87                 }
 88                 //画图片的边框线
 89                 graphic.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
 90                 //将图片验证码保存为流Stream返回
 91                 System.IO.MemoryStream ms = new System.IO.MemoryStream();
 92                 image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
 93                 return ms;
 94             }
 95             finally
 96             {
 97                 graphic.Dispose();
 98                 image.Dispose();
 99             }
100         }
101 
102         /// <summary>
103         /// 获取验证码
104         /// </summary>
105         /// <returns></returns>
106         public ActionResult GetValidateCode()
107         {
108             string code = MakeCode(4);
109             Session["ValidateCode"] = code;
110             MemoryStream ms = CreateCodeImg(code);
111             return File(ms.ToArray(), @"image/jpeg");
112         }
113 
114     }
115 }

2.前端Html页面

1 <span>验证码:<input name="ValidateCode" type="text" value="" class="input2" id="txtValidateCode" size="12" maxlength="5"   >
2                             <img src="../Tool/GetValidateCode" style="cursor: pointer;" name="checkcode" border="0"
3                                 id="valiCode" alt="验证码" class="Ysm" />
4                             </span>
1  $(function () {
2             $("#valiCode").bind("click", function () {
3                 this.src = "../Tool/GetValidateCode?time=" + (new Date()).getTime();
4             });
5         });

3.后台验证输入的验证码

 1 string validateCode = (string)Request.Form["ValidateCode"]??"";
 2             if (string.IsNullOrEmpty(validateCode))
 3             {
 4                 ModelState.AddModelError("validateCodeError","验证码错误!");
 5                 return View();
 6             }
 7             if (Session["ValidateCode"]!=null&&Session["ValidateCode"].ToString().ToLower() != validateCode.ToLower())
 8             {
 9                 ModelState.AddModelError("validateCodeError", "验证码错误!");
10                 return View();
11             }
原文地址:https://www.cnblogs.com/CeleryCabbage/p/4925464.html