本着简洁直接,我们就直奔主题吧!

  下面是一个生成数字和字母随机组合的验证码类源代码:

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web.UI;
using System.Drawing.Drawing2D;
using System.IO; namespace Forcheng.Code
{
/// <summary>
/// 生成验证码的类
/// </summary>
public class ValidateCode
{
/// <summary>
/// 生成验证码
/// </summary>
/// <param name="length">指定验证码的长度</param>
/// <returns></returns>
public string CreateValidateCode(int length)
{
const string validateTemplate = "23456789abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ";
string validateStr = "";
int n = validateTemplate.Length - ; //设置随机值生成器
int seekSeek = unchecked((int)DateTime.Now.Ticks);
Random seekRand = new Random(seekSeek);
int beginSeek = ; //生成随机验证码
for (int i = ; i < length; i++)
{
beginSeek = seekRand.Next(, n);
validateStr += validateTemplate.Substring(beginSeek, );
}
return validateStr;
} /// <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 * 13.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();
}
}
}
}

  下面是使用验证码类的后台实例代码(生成一个5位的图片验证码):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Forcheng.Code; namespace Test.Controllers
{
public class HomeController : Controller
{
/// <summary>
/// 获取图片验证码
/// </summary>
/// <returns></returns>
public ActionResult GetValidateCode(string codeClass)
{
ValidateCode vCode = new ValidateCode();
string code = vCode.CreateValidateCode();
byte[] bytes = vCode.CreateValidateGraphic(code);
return File(bytes, @"image/jpeg");
} }
}

  下面是前台页面使用的实例代码:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>图片验证码</title>
</head> <body>
<img id="valiCode" class="validcode" src="/Home/GetValidateCode" alt="验证码" title="点击刷新" />
<script type="text/javascript">
$(document).ready(function () {
$("#valiCode").bind("click", function () {
this.src = "/Home/GetValidateCode?&time=" + (new Date()).getTime();
});
});
</script>
</body>
</html>

  效果截图(做的另一个找回密码页面,不是上面的前台代码效果):

  

   这次的分享就到这吧,我们下次继续。

  <我的博客主页>:http://www.cnblogs.com/forcheng/

ASP.NET MVC 模块与组件(二)——定制图片验证码的更多相关文章

  1. ASP.NET MVC 模块与组件(一)——发送邮件

    我的见解: 模块化与组件化是编程的一种思想:提高代码的重用性,提高开发效率. 常见的模块化就是函数与各种类型的封装,若是代码具有更高的重用价值(能够提供给别人使用),建议可以考虑封装成动态链接库(dl ...

  2. ASP.NET MVC案例教程(二)

    ASP.NET MVC案例教程(二) 让第一个页面跑起来 现在,我们来实现公告系统中的第一个页面——首页.它非常简单,只包括所有公告分类的列表,并且每个列表项是一个超链接.其中分类数据是用我们的Moc ...

  3. Asp.net mvc 知多少(二)

    本系列主要翻译自<ASP.NET MVC Interview Questions and Answers >- By Shailendra Chauhan,想看英文原版的可访问http:/ ...

  4. asp.net mvc 模型验证组件——FluentValidation

    asp.net mvc 模型验证组件——FluentValidation 示例 using FluentValidation; public class CustomerValidator: Abst ...

  5. asp.net MVC通用分页组件 使用方便 通用性强

    asp.net MVC通用分页组件 使用方便 通用性强   该分页控件的显示逻辑: 1 当前页面反色突出显示,链接不可点击 2 第一页时首页链接不可点击 3 最后一页时尾页链接不可点击 4 当前页面左 ...

  6. 转:【译】Asp.net MVC 利用自定义RouteHandler来防止图片盗链

    [译]Asp.net MVC 利用自定义RouteHandler来防止图片盗链   你曾经注意过在你服务器请求日志中多了很多对图片资源的请求吗?这可能是有人在他们的网站中盗链了你的图片所致,这会占用你 ...

  7. Asp.Net MVC学习总结(二)——控制器与动作(Controller And Action)

    一.理解控制器 1.1.什么是控制器 控制器是包含必要的处理请求的.NET类,控制器的角色封装了应用程序逻辑,控制器主要是负责处理请求,实行对模型的操作,选择视图呈现给用户. 简单理解:实现了ICon ...

  8. [译]Asp.net MVC 之 Contorllers(二)

    URL路由模块 取代URL重写 路由请求 URL路由模块的内部结构 应用程序路由 URL模式和路由 定义应用程序路由 处理路由 路由处理程序 处理物理文件请求 防止路由定义的URL 属性路由 书接上回 ...

  9. ASP.NET MVC +EasyUI 权限设计(二)环境搭建

    请注明转载地址:http://www.cnblogs.com/arhat 今天突然发现博客园出问题了,老魏使用了PC,手机,平板都访问博客园了,都是不能正常的访问,原因是不能加载CSS,也就是不能访问 ...

随机推荐

  1. WKInterfaceImage 无法更新图片的问题

    最近涉及到AppleWatch的相关项目,但有个奇怪问题无法解决,而且无法理解: 根据不同的用户操作,需要修改播放器的专辑图片. 不知道跟我的项目需求是不是有关系:我需要轮询共享空间,以拿取同步数据, ...

  2. ASP.NET MVC从视图传递多个模型到Controller

    从后台组织好数据然后传递到页面倒是水到渠成很方便,因为MVC自身就将这样的需求内建到了这个系统中.我只需要在后台组织好一个List 或IEnumerable类型的变量,将需要传递的数据模型扔进去便可. ...

  3. Azure China (10) 使用Azure China SAS Token

    <Windows Azure Platform 系列文章目录> 本文介绍的是国内由世纪互联运维的Azure China 注意:本文介绍的是Azure China Storage Priva ...

  4. synchronized同步对象锁

    package com.system.util; import com.common.Constants; import com.util.Cache; /** * 创建同步对象锁 * * @auth ...

  5. 上学时的HTML+JS+CSS(小总结)

    html:超文本标记语言 基本标签: { 文本标签:<pre></pre>:原封不动的保留空白区域.      <br />:换行.      <hr wid ...

  6. IOS Animation-CABasicAnimation、CAKeyframeAnimation详解&区别&联系

    1.先看看网上流传的他们的继承图: 从上面可以看出CABasicAnimation与CAKeyframeAnimation都继承于CAPropertyAnimation.而CAPropertyAnim ...

  7. iOS-性能优化3

    iOS-性能优化3 UITableView性能优化与卡顿问题 1.最常用的就是cell的重用, 注册重用标识符 如果不重用cell时,每当一个cell显示到屏幕上时,就会重新创建一个新的cell 如果 ...

  8. iOS---NSAutoreleasePool自动释放原理及详解

    前言:当您向一个对象发送一个autorelease消息时,Cocoa就会将该对象的一个引用放入到最新的自动释放池.它仍然是个正当的对象,因此自动释放池 定义的作用域内的其它对象可以向它发送消息.当程序 ...

  9. spring cvc-elt.1: Cannot find the declaration of element 'beans'解决办法

    转载自http://blog.csdn.net/legendj/article/details/9950963 今天在写spring aop示例的时候,在spring.xml文件中添加spring a ...

  10. 快速入门系列--MVC--01概述

    虽然使用MVC已经不少年,相关技术的学习进行了多次,但是很多技术思路的理解其实都不够深入.其实就在MVC框架中有很多设计模式和设计思路的体现,例如DependencyResolver类就包含我们常见的 ...