1 ValidateCode.cs

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO; namespace Common
{
/// <summary>
/// 生成验证码的类
/// </summary>
public class ValidateCode
{
public ValidateCode()
{
}
/// <summary>
/// 验证码的最大长度
/// </summary>
public int MaxLength
{
get { return ; }
}
/// <summary>
/// 验证码的最小长度
/// </summary>
public int MinLength
{
get { return ; }
}
/// <summary>
/// 生成验证码
/// </summary>
/// <param name="length">指定验证码的长度</param>
/// <returns></returns>
public string CreateValidateCode(int length)
{
int[] randMembers = new int[length];
int[] validateNums = new int[length];
string validateNumberStr = "";
//生成起始序列值
int seekSeek = unchecked((int)DateTime.Now.Ticks);
Random seekRand = new Random(seekSeek);
int beginSeek = (int)seekRand.Next(, Int32.MaxValue - length * );
int[] seeks = new int[length];
for (int i = ; i < length; i++)
{
beginSeek += ;
seeks[i] = beginSeek;
}
//生成随机数字
for (int i = ; i < length; i++)
{
Random rand = new Random(seeks[i]);
int pownum = * (int)Math.Pow(, length);
randMembers[i] = rand.Next(pownum, Int32.MaxValue);
}
//抽取随机数字
for (int i = ; i < length; i++)
{
string numStr = randMembers[i].ToString();
int numLength = numStr.Length;
Random rand = new Random();
int numPosition = rand.Next(, numLength - );
validateNums[i] = Int32.Parse(numStr.Substring(numPosition, ));
}
//生成验证码
for (int i = ; i < length; i++)
{
validateNumberStr += validateNums[i].ToString();
}
return validateNumberStr;
}
/// <summary>
/// 创建验证码的图片
/// </summary>
/// <param name="containsPage">要输出到的page对象</param>
/// <param name="validateNum">验证码</param>
public byte[] CreateValidateGraphic(string validateCode)
{
Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 12.0), );
Graphics g = Graphics.FromImage(image);
try
{
//生成随机生成器
Random random = new Random();
//清空图片背景色
g.Clear(Color.White);
//画图片的干扰线
for (int i = ; i < ; i++)
{
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height);
g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
}
Font font = new Font("Arial", , (FontStyle.Bold | FontStyle.Italic));
LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(, , image.Width, image.Height),
Color.Blue, Color.DarkRed, 1.2f, true);
g.DrawString(validateCode, font, brush, , );
//画图片的前景干扰点
for (int i = ; i < ; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);
image.SetPixel(x, y, Color.FromArgb(random.Next()));
}
//画图片的边框线
g.DrawRectangle(new Pen(Color.Silver), , , image.Width - , image.Height - );
//保存图片数据
MemoryStream stream = new MemoryStream();
image.Save(stream, ImageFormat.Jpeg);
//输出图片流
return stream.ToArray();
}
finally
{
g.Dispose();
image.Dispose();
}
}
/// <summary>
/// 得到验证码图片的长度
/// </summary>
/// <param name="validateNumLength">验证码的长度</param>
/// <returns></returns>
public static int GetImageWidth(int validateNumLength)
{
return (int)(validateNumLength * 12.0);
}
/// <summary>
/// 得到验证码的高度
/// </summary>
/// <returns></returns>
public static double GetImageHeight()
{
return 22.5;
}
}
}

2 在Controller.cs中,添加Action,用来设置将生成的验证码存入Session,并输出验证码图片

        [AllowAnonymous]
public ActionResult GetValidateCode()
{
ValidateCode vCode = new ValidateCode();
string code = vCode.CreateValidateCode();
Session["ValidateCode"] = code;
byte[] bytes = vCode.CreateValidateGraphic(code);
return File(bytes, @"image/jpeg");
}

3 调用方式为:在需要使用验证码的页面中,加入<img>标签:

<img id="valiCode" style="cursor: pointer;" class="col-md-2 control-label" src="~/Account/GetValidateCode" alt="验证码" />

4 效果如图

5 验证码匹配

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (model.ValidCode != Session["ValidateCode"].ToString())
{
ModelState.AddModelError("", "验证码不正确.");
return View(model);
} if (ModelState.IsValid)
{
var user = await UserManager.FindAsync(model.UserName, model.Password);
if (user != null)
{
await SignInAsync(user, model.RememberMe);
return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError("", "Invalid username or password.");
}
} // 如果我们进行到这一步时某个地方出错,则重新显示表单 return View(model);
}

6 点击图片刷新验证码

@section Scripts {
@Scripts.Render("~/bundles/jqueryval") <script type="text/javascript">
$(function () {
$("#valiCode").bind("click", function () {
this.src = "../Account/GetValidateCode?time=" + (new Date()).getTime();
});
});
</script> }

ASP.NET MVC5 生成验证码的更多相关文章

  1. (一)【转】asp.net mvc生成验证码

    网站添加验证码,主要为防止机器人程序批量注册,或对特定的注册用户用特定程序暴力破解方式,以进行不断的登录.灌水等危害网站的操作.验证码被广泛应用在注册.登录.留言等提交信息到服务器端处理的页面中.   ...

  2. Asp.net mvc生成验证码

    1.生成验证码类 using System; using System.Collections.Generic; using System.Linq; using System.Text; using ...

  3. ASP.NET MVC 生成验证码

    using System.Web.Mvc; using System.Drawing; using System; using System.Drawing.Imaging; using Models ...

  4. ASP.NET ashx实现无刷新页面生成验证码

    现在大部分网站登陆时都会要求输入验证码,在网上也看了一些范例,现在总结一下如何实现无刷新页面生成验证码. 效果图: 实现方式: 前台: <div> <span>Identify ...

  5. ASP.Net MVC 生成安全验证码

    ---------html <td>验证码:</td>            <td>                <img src="/Logi ...

  6. 详细说说如何生成验证码—ASP.NET细枝末节(4)

    前言 今天小编详细的说一下,ASP.NET网站开发过程中生成验证码的全部问题. 本文的目标,是让读者了解,生成验证码涉及的全部基础知识问题. 当然这里说的是比较简单的验证码. 真正符合要求的验证码,涉 ...

  7. ASP.NET MVC生成安全验证码

    html部分: <!DOCTYPE html> <html lang="en"> <head> <meta charset="U ...

  8. 012. asp.net生成验证码图片(汉字示例/字母+数字)

    protected void Page_Load(object sender, EventArgs e) { //生成验证码图片的基本步骤 string checkCode = "新年快乐& ...

  9. Asp.net 生成验证码

    生成验证码一般来说大体有这么几步: 1.生成验证码字符串,一般由四个或更多随机字符拼凑而成: 2.填充图片背景,并绘制图片的背景噪音线: 3.将验证码绘制到图片中: 4.绘制前景噪点: 5.返回图片流 ...

随机推荐

  1. 单片微机原理P3:80C51外部拓展系统

    外部拓展其实是个相对来说很好玩的章节,可以真正开始用单片机写程序了,比较重要的是外部存储器拓展,81C55拓展,矩阵键盘,动态显示,DAC和ADC.   0. IO接口电路概念与存储器拓展 1. 为什 ...

  2. 配色问题lingo实现

    大家好,我是小鸭酱,博客地址为:http://www.cnblogs.com/xiaoyajiang !调配颜色 要依次调配红.兰.白.黑.黄五种颜色 红  兰  白  黑  黄 红  0  6  1 ...

  3. 【iOS开发】单例模式设计(ARC & MRC)

    适用于ARC & MRC // 帮助实现单例设计模式 // .h文件的实现 #define SingletonH(methodName) + (instancetype)shared##met ...

  4. Linux下装VirtualBox

    一:下载 进入VirtualBox的下载地址:https://www.virtualbox.org/ 点击左侧的download, 选择适合自己系统的版本,我的是红帽,故选择: 进行下载. 二:安装 ...

  5. Android CursorAdapter

    CursorAdapter 继承于BaseAdapter是个虚类,它为cursor和ListView提供了连接的桥梁.            public abstract class     Cur ...

  6. The square chest

    The square chest Sophia pressed the button in front of her, slamming her fist against it. The door r ...

  7. 单线多拨,傻瓜式openwrt单线多拨叠加速率教程

    http://bbs.pceva.com.cn/thread-98362-1-1.html

  8. 107个常用Javascript语句

    1.document.write( " "); 输出语句 2.JS中的注释为// 3.传统的HTML文档顺序是:document- >html- >(head,body ...

  9. jsp中全局变量和局部变量的设置

  10. Hdu2860-Regroup(种类并查集)

    Problem Description When ALPC42 got to a panzer brigade, He was asked to build software to help them ...