首先新建一个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. appium 支持输入中文

    加入: desired_caps['unicodeKeyboard'] = True desired_caps['resetKeyboard'] = True 使用输入中文: input_txt = ...

  2. PageMethods

    主要是用到ScriptManger,老知识Mark一下,ScriptManager要EnablePageMethods="true" 后台 using System.Web.Scr ...

  3. BZOJ4016:[FJOI2014]最短路径树问题

    浅谈树分治:https://www.cnblogs.com/AKMer/p/10014803.html 题目传送门:https://www.lydsy.com/JudgeOnline/problem. ...

  4. .NETFramework-Web.Services:WebMethodAttribute

    ylbtech-.NETFramework-Web.Services:WebMethodAttribute 1.程序集 System.Web.Services, Version=4.0.0.0, Cu ...

  5. Windows下搭建svn服务器端--创建自…

    Windows下搭建svn服务器端 1.软件 1)服务端:Subversion subversion.apache.org - Getting Subversion - Binary Packages ...

  6. iOS公司账号($99)/企业账号($299)申请

    公司账号($99)与企业账号($299)申请基本大同小异,最主要的差别就在于入口不一样 一.注册Apple ID 在iOSAppStore个人开发者账号申请中已经介绍过注册App ID的流程,这里不再 ...

  7. shell初级-----构建基本脚本

    使用多个命令 如果想要多个命令同时运行,可以把它们放在一行,用分号隔开. date;who 创建shell脚本文件 创建shell脚本时,必须在文件第一行指定要使用的shell #!/bin/bash ...

  8. Automake使用(中级)

    工程地址 automake语言国际化 最初工程目录结构 $ ls -l total 16 drwxrwxr-x. 2 fedora fedora 4096 May 10 10:38 build-aux ...

  9. Find First and Last Position of Element in Sorted Array

    问题:给定一个有序数组和一个目标值,输出目标值在数组中的起始位置和终止位置,如果目标值不在数组中,则输出[-1,-1] 示例: 输入:nums = [1,2,3,5,5,7] target = 5 输 ...

  10. android实现简单计算器

    前台代码如下 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:andro ...