Asp.net mvc生成验证码

时间:2022-12-28 07:18:45

1.生成验证码类

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.IO;
using System.Drawing;
using System.Web; namespace SimpleNews.FrontEnd
{
public class ToolController : MyControllerBase
{
/// <summary>
/// 生成验证码字符串
/// </summary>
/// <param name="codeLen">验证码字符长度</param>
/// <returns>返回验证码字符串</returns>
private static string MakeCode(int codeLen)
{
if (codeLen < )
{
return string.Empty;
}
int number;
StringBuilder sbCheckCode = new StringBuilder();
Random random = new Random(); for (int index = ; index < codeLen; index++)
{
number = random.Next(); if (number % == )
{
sbCheckCode.Append((char)('' + (char)(number % ))); //生成数字
}
else
{
sbCheckCode.Append((char)('A' + (char)(number % ))); //生成字母
}
}
return sbCheckCode.ToString();
} ///<summary>
/// 获取验证码图片流
/// </summary>
/// <param name="checkCode">验证码字符串</param>
/// <returns>返回验证码图片流</returns>
public static MemoryStream CreateCodeImg(string checkCode)
{
if (string.IsNullOrEmpty(checkCode))
{
return null;
}
Bitmap image = new Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), );
Graphics graphic = Graphics.FromImage(image);
try
{
Random random = new Random();
graphic.Clear(Color.White);
int x1 = , y1 = , x2 = , y2 = ;
for (int index = ; index < ; index++)
{
x1 = random.Next(image.Width);
x2 = random.Next(image.Width);
y1 = random.Next(image.Height);
y2 = random.Next(image.Height); graphic.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
}
Font font = new Font("Arial", , (FontStyle.Bold | FontStyle.Italic));
System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(, , image.Width, image.Height), Color.Red, Color.DarkRed, 1.2f, true);
graphic.DrawString(checkCode, font, brush, , ); int x = ;
int y = ; //画图片的前景噪音点
for (int i = ; i < ; i++)
{
x = random.Next(image.Width);
y = random.Next(image.Height); image.SetPixel(x, y, Color.FromArgb(random.Next()));
}
//画图片的边框线
graphic.DrawRectangle(new Pen(Color.Silver), , , image.Width - , image.Height - );
//将图片验证码保存为流Stream返回
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
return ms;
}
finally
{
graphic.Dispose();
image.Dispose();
}
} /// <summary>
/// 获取验证码
/// </summary>
/// <returns></returns>
public ActionResult GetValidateCode()
{
string code = MakeCode();
Session["ValidateCode"] = code;
MemoryStream ms = CreateCodeImg(code);
return File(ms.ToArray(), @"image/jpeg");
} }
}

2.前端Html页面

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

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

 string validateCode = (string)Request.Form["ValidateCode"]??"";
if (string.IsNullOrEmpty(validateCode))
{
ModelState.AddModelError("validateCodeError","验证码错误!");
return View();
}
if (Session["ValidateCode"]!=null&&Session["ValidateCode"].ToString().ToLower() != validateCode.ToLower())
{
ModelState.AddModelError("validateCodeError", "验证码错误!");
return View();
}