首先新建一个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中验证码的简单使用的更多相关文章

  1. MVC中验证码

    MVC中验证码的实现(经常用,记录备用)   一.目录 1.多层架构+MVC+EF+AUTOFAC+AUTOMAPPER: 2.MVC中验证码的实现(经常用,记录备用) 3.Ligerui首页的快速搭 ...

  2. MVC中验证码的实现(经常用,记录备用)

    一.目录 1.多层架构+MVC+EF+AUTOFAC+AUTOMAPPER: 2.MVC中验证码的实现(经常用,记录备用) 3.Ligerui首页的快速搭建 二 正文 Ok,我们的验证码开始,这篇文章 ...

  3. asp.net mvc 中 一种简单的 URL 重写

    asp.net mvc 中 一种简单的 URL 重写 Intro 在项目中想增加一个公告的功能,但是又不想直接用默认带的那种路由,感觉好low逼,想弄成那种伪静态化的路由 (别问我为什么不直接静态化, ...

  4. MVC中验证码的生成

    在项目中验证码的生成通常是需要页面无刷新的,所以验证码图片实际是跟在某个input后面的img,通过控制该img来控制验证码显示的位置,例如: <div> <input id=&qu ...

  5. asp.net -mvc框架复习(5)-ASP.NET MVC中的视图简单使用

    1.视图分类 ASPX视图(现在讲解) Razor视图(后面讲解) ASPX 视图: 2.@page指令 作用:页面的声明 要求:必须放在第一行,常用指令属性如下: 3.服务器端内嵌语法 小脚本:在A ...

  6. .net mvc中一种简单的工作流的设计

    开篇前的废话:工作流是我们在做互联网应用开发时经常需要用到的一种技术,复杂的工作流我们基本是借助一些开源的 工作流项目来做,比如 ccflow等,但是有时候,我们只需要实现一些简单的工作流流程,这时候 ...

  7. MVC中使用MVCPager简单分页

    一.建立数据库以及建立MVC项目 自己随便建立一个数据库,并且添加数据.我建立的数据库如下. 二.建立LINQ to SQL映射. 然后一步步点确定 三.编写代码 在Controllers中建立控制器 ...

  8. mvc中hangfire全局简单配置

    public void Configuration(IAppBuilder app)       {           ConfigureAuth(app);           //指定使用Sql ...

  9. MVC中Cookies的简单读写操作

    写入 public static void WriteCookie(string cn, string cv, DateTime Time) { HttpCookie cookie = new Htt ...

随机推荐

  1. bjwc Day3 & 4 妈妈我这是来了个什么地方呀

    真·bjwc开始了 Day3 T1啥啥啥 第k大斜率?想都没想码了个暴力,然后爆零...暴力都能错,退役 T2看着像网络流就扔了个网络流大暴力上去,六七十分的样子然后蜜汁wa T3题面说“想都没想就弄 ...

  2. 构建基于虚拟用户的vsftpd服务器

    安装: [root@server ~]# yum install -y vsftpd [root@server ~]# rpm -ql vsftpd /etc/logrotate.d/vsftpd / ...

  3. MyEclipse修改Servlet模板

    进入myeclipse的安装路径 然后进入plugins文件夹 打开搜索框,输入 *wizard* 找到名字是 com.genuitec.eclipse.wizards_11.5.0.me201310 ...

  4. 【转】Android Menu

    Menu由两种形式,Option menu和Context menu.前者是按下设备的Menu硬按钮弹出,后者是长按widget弹出. Option Menu 当我们按下Menu的硬件按钮时,Opti ...

  5. 32.Docker安装MongoDb

    从hub.docker.com上去找镜像 阿里云的国内的镜像地址 填上去之后,然后重启下docker就可以了 docker images列出本地的镜像 拉取mango的镜像 运行这个镜像 docker ...

  6. js关于为DOM对象添加自定义属性的方式和区别

    DOM对象的三种在添加自定义属性的方式 一是 通过 “.”+“属性名” 二是 setAttribute()(getAttribute()获取) 三是 直接在元素标签上加属性  如:<div  n ...

  7. 多进程小例子--fork+pipe

    1 #include<stdio.h>  2 #include<unistd.h>  3   4 #define m 6  5 int main()  6 {  7       ...

  8. The web.config file for this project is missing the required DirectRequestModule.

    The web.config file for this project is missing the required DirectRequestModule.   将应用程序集的模式由集成改为经典 ...

  9. ue4 log

    在Unreal Engine 4中,打Log很方便,可以使用宏: [cpp] view plain copy print? UE_LOG(LogTemp, Warning, TEXT("Yo ...

  10. 使用Git版本控制工具管理GitHub

      使用Git版本控制工具管理GitHu Git是一个分步式的管理系统:只要上传操作得当,所有的都可以相当于是中央服务器,成员代码共享,A写的代码B也有,一般把一个人当做主机,其他人通过该主机拼装代码 ...