MVC中验证码的简单使用
首先新建一个MVC项目


添加类:验证码帮助类(ValidateCodeHelper)
using System;
using System.Collections.Generic;
using System.IO; using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging; namespace ValidateCodeDemo
{
public class ValidateCodeHelper
{
/// <summary>
/// 生成验证码
/// </summary>
/// <param name="length">指定验证码的长度</param>
/// <returns></returns>
public static 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="validateCode">验证码</param>
public static 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();
}
}
}
}
在HomeController中新增两个Action
public ActionResult ValidateCodeTest()
{
return View();
} public ActionResult GetValidateCode()
{
//获取随机验证码
string code = ValidateCodeHelper.CreateValidateCode();
//将验证码放到Session中以便提交校验
Session["ValidateCode"] = code;
//绘制验证码
byte[] bytes = ValidateCodeHelper.CreateValidateGraphic(code);
//返回验证码image
return File(bytes, @"image/jpeg");
}
第一个返回视图,右击第一个方法名添加视图。

在视图中添加img标签,代码如下:src指向第二个方法。
<img id="valiCode" style="cursor: pointer; margin-bottom: -5px; padding-left: 12px;" src="/Home/GetValidateCode" alt="验证码" />
最后修改默认路由。
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "ValidateCodeTest", id = UrlParameter.Optional }
);
}
F5执行结果:

MVC中验证码的简单使用的更多相关文章
- MVC中验证码
MVC中验证码的实现(经常用,记录备用) 一.目录 1.多层架构+MVC+EF+AUTOFAC+AUTOMAPPER: 2.MVC中验证码的实现(经常用,记录备用) 3.Ligerui首页的快速搭 ...
- MVC中验证码的实现(经常用,记录备用)
一.目录 1.多层架构+MVC+EF+AUTOFAC+AUTOMAPPER: 2.MVC中验证码的实现(经常用,记录备用) 3.Ligerui首页的快速搭建 二 正文 Ok,我们的验证码开始,这篇文章 ...
- asp.net mvc 中 一种简单的 URL 重写
asp.net mvc 中 一种简单的 URL 重写 Intro 在项目中想增加一个公告的功能,但是又不想直接用默认带的那种路由,感觉好low逼,想弄成那种伪静态化的路由 (别问我为什么不直接静态化, ...
- MVC中验证码的生成
在项目中验证码的生成通常是需要页面无刷新的,所以验证码图片实际是跟在某个input后面的img,通过控制该img来控制验证码显示的位置,例如: <div> <input id=&qu ...
- asp.net -mvc框架复习(5)-ASP.NET MVC中的视图简单使用
1.视图分类 ASPX视图(现在讲解) Razor视图(后面讲解) ASPX 视图: 2.@page指令 作用:页面的声明 要求:必须放在第一行,常用指令属性如下: 3.服务器端内嵌语法 小脚本:在A ...
- .net mvc中一种简单的工作流的设计
开篇前的废话:工作流是我们在做互联网应用开发时经常需要用到的一种技术,复杂的工作流我们基本是借助一些开源的 工作流项目来做,比如 ccflow等,但是有时候,我们只需要实现一些简单的工作流流程,这时候 ...
- MVC中使用MVCPager简单分页
一.建立数据库以及建立MVC项目 自己随便建立一个数据库,并且添加数据.我建立的数据库如下. 二.建立LINQ to SQL映射. 然后一步步点确定 三.编写代码 在Controllers中建立控制器 ...
- mvc中hangfire全局简单配置
public void Configuration(IAppBuilder app) { ConfigureAuth(app); //指定使用Sql ...
- MVC中Cookies的简单读写操作
写入 public static void WriteCookie(string cn, string cv, DateTime Time) { HttpCookie cookie = new Htt ...
随机推荐
- POJ1195Mobile phones (从二维树状数组到cdq分治)
Suppose that the fourth generation mobile phone base stations in the Tampere area operate as follows ...
- BZOJ3648:寝室管理
浅谈树分治:https://www.cnblogs.com/AKMer/p/10014803.html 题目传送门:https://www.lydsy.com/JudgeOnline/problem. ...
- 【转】Pro Android学习笔记(三):了解Android资源(上)
在Android开发中,资源包括文件或者值,它们和执行应用捆绑,无需在源代码中写死,因此我们可以改变或替换他们,而无需对应用重新编译. 了解资源构成 参考阅读Android学习笔记(三八):资源res ...
- .NETFramework:Random
ylbtech-.NETFramework:Random 1.程序集 mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c ...
- java性能调优的11个建议
1.在必要之前,先不要优化 2.使用分析器来找到真正的瓶颈 3 .为整个应用程序创建性能测试套件 4.首先解决最大的瓶颈问题 5.使用StringBuilder以编程方式连接字符串 Str ...
- Eclipse常用配置(1)
1.代码自动提示 在我们忘记方法名或者想偷懒时,代码自动提示很管用.不过Eclipse默认是输入"."后才会出现包或类成员的提示,也就意味着我们必须先输入一个完整的类名,提示才能出 ...
- python3中,pycharm中怎么连接数据库
因为python3现在还不能直接连接数据库,所有如果想连接,就只能通过以下方法: 在APP中的,__init__.py中,添加以下代码就可以: import pymysql pymysql.insta ...
- 反射-Class
package classes; public class ClassDemo1 { public static void main(String[] args){ Foo foo1 = new Fo ...
- 原生app与WebApp的区别
Native App开发Native App开发即我们所称的传统APP开发模式(原生APP开发模式),该开发针对IOS.Android等不同的手机操作系统要采用不同的语言和框架进行开发,该模式通常是由 ...
- 《精通Spring4.X企业应用开发实战》读后感第五章(Bean作用域)