C#生成简单验证码

摘要:
无论是登录还是在网站上注册,我们经常会遇到各种验证码。事实上,生成验证代码对于C#来说非常简单。下面是我如何学习生成验证代码的一个简单示例。封装的辅助类代码,如下:1使用System;2使用System.Collections。通用的3使用系统。绘画4使用系统图纸。图纸2D;5使用系统。Linq;6使用System.Security。密码学;7使用系统。文本8使用System.Threading。任务;910命名空间Ninesky。Common11{12publicclassSecurity13{14///<summary>15///创建验证码字符16///使用伪随机数生成器生成验证码字符串。

我们平时无论是网站登录还是注册,都会频繁的遇到各式各样的验证码 ,其实生成验证码对于C#来说非常简单。

下面就是我学习生成验证码的简单实例。

封装的辅助类代码,如下:

C#生成简单验证码第1张C#生成简单验证码第2张
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Drawing;
 4 using System.Drawing.Drawing2D;
 5 using System.Linq;
 6 using System.Security.Cryptography;
 7 using System.Text;
 8 using System.Threading.Tasks;
 9 
10 namespace Ninesky.Common
11 {
12     public class Security
13     {
14         /// <summary>
15         /// 创建验证码字符
16         /// 利用伪随机数生成器生成验证码字符串。
17         /// </summary>
18         /// <param name="length">字符长度</param>
19         /// <returns>验证码字符</returns>
20         public static string CreateVerificationText(int length)
21         {
22             char[] _verification = new char[length];
23             char[] _dictionary = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T'
24 , 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'
25 , 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
26             Random _random = new Random();
27             for (int i = 0; i < length; i++)
28             {
29                 _verification[i] = _dictionary[_random.Next(_dictionary.Length - 1)];
30             }
31             return new string(_verification);
32         }
33         /// <summary>
34         /// 创建验证码图片
35         /// 思路是使用GDI+创建画布,使用伪随机数生成器生成渐变画刷,然后创建渐变文字。
36         /// </summary>
37         /// <param name="verificationText">验证码字符串</param>
38         /// <param name="width">图片宽度</param>
39         /// <param name="height">图片长度</param>
40         /// <returns>图片</returns>
41         public static Bitmap CreateVerificationImage(string verificationText, int width, int height)
42         {
43             Pen _pen = new Pen(Color.Black);
44             Font _font = new Font("Arial", 14, FontStyle.Bold);
45             Brush _brush = null;
46             Bitmap _bitmap = new Bitmap(width, height);
47             Graphics _g = Graphics.FromImage(_bitmap);
48             SizeF _totalSizeF = _g.MeasureString(verificationText, _font);
49             SizeF _curCharSizeF;
50             //PointF _startPointF = new PointF((width - _totalSizeF.Width) / 2, (height - _totalSizeF.Height) / 2);
51             PointF _startPointF = new PointF(0, (height - _totalSizeF.Height) / 2);
52             //随机数产生器
53             Random _random = new Random();
54             _g.Clear(Color.White);
55             for (int i = 0; i < verificationText.Length; i++)
56             {
57                 _brush = new LinearGradientBrush(new Point(0, 0), new Point(1, 1), Color.FromArgb(_random.Next(255), _random.Next(255), _random.Next(255)), Color.FromArgb(_random.Next(255), _random.Next(255), _random.Next(255)));
58                 _g.DrawString(verificationText[i].ToString(), _font, _brush, _startPointF);
59                 _curCharSizeF = _g.MeasureString(verificationText[i].ToString(), _font);
60                 _startPointF.X += _curCharSizeF.Width;
61             }
62             _g.Dispose();
63             return _bitmap;
64         }
65         /// <summary>
66         /// 256位散列加密
67         /// </summary>
68         /// <param name="plainText">明文</param>
69         /// <returns>密文</returns>
70         public static string Sha256(string plainText)
71         {
72             SHA256Managed _sha256 = new SHA256Managed();
73             byte[] _cipherText = _sha256.ComputeHash(Encoding.Default.GetBytes(plainText));
74             return Convert.ToBase64String(_cipherText);
75         }
76     }
77 }
Security

 后台控制器代码,如下:

C#生成简单验证码第3张C#生成简单验证码第4张
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Drawing;
 4 using System.Linq;
 5 using System.Web;
 6 using System.Web.Mvc;
 7 using Ninesky.Common;
 8 
 9 namespace WebTest.Controllers
10 {
11     public class VerificationCodeController : Controller
12     {
13         List<string> userlist = new List<string>();
14         //
15         // GET: /VerificationCode/
16 
17         public ActionResult Index()
18         {
19             ViewData["VerificationCode"] = TempData["VerificationCode"];
20             return View();
21         }
22         /// <summary>
23         /// 验证码
24         /// </summary>
25         /// <returns></returns>
26         public ActionResult VerificationCode()
27         {
28             string verificationCode = Security.CreateVerificationText(6);
29             Bitmap _img = Security.CreateVerificationImage(verificationCode, 140, 30);
30             _img.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
31             TempData["VerificationCode"] = verificationCode.ToUpper();
32             return null;
33         }
34 
35         public string Register(FormCollection coll)
36         {
37             string AccountNumber = coll["AccountNumber"].Trim().ToString();
38             string Password = coll["Password"].Trim().ToString();
39             string ConfirmPassword = coll["ConfirmPassword"].Trim().ToString();
40             string verificationcode = coll["verificationcode"].Trim().ToString().ToUpper();
41             if (string.IsNullOrEmpty(AccountNumber))
42             {
43                 return "用户名称不能为空!";
44             }
45             else if (userlist.Count > 0 && userlist.Where(m => m == AccountNumber).First() != null)
46             {
47                 return "该用户已存在!";
48             }
49             else if (!Password.Equals(ConfirmPassword))
50             {
51                 return "两次输入密码不一致!";
52             }
53             else if (!verificationcode.Equals(TempData["VerificationCode"].ToString()))
54             {
55                 return "验证码输入错误!";
56             }
57             else
58             {
59                 userlist.Add(AccountNumber);
60                 return "恭喜你,注册成功!";
61             }
62         }
63     }
64 }
VerificationCodeController

 前台页面代码,如下:

C#生成简单验证码第5张C#生成简单验证码第6张
  1 @{
  2     ViewBag.Title = "注册页面";
  3 }
  4 <script src="~/Scripts/jquery-3.1.1.min.js"></script>
  5 <style type="text/css">
  6     .txt
  7     {
  8         height: 30px;
  9     }
 10 
 11     .td td
 12     {
 13         max-height: 15px;
 14         padding: 0px;
 15         margin: 0px;
 16     }
 17 
 18     .img
 19     {
 20         padding: 0px;
 21         margin: 0px;
 22     }
 23 </style>
 24 <script type="text/javascript">
 25     $(function () {
 26         $("#Agreest").change(function () {
 27             if ($("#Agreest").checked) {
 28                 $("#btnRegister").attr({ "disabled": "disabled" });
 29                 //$("#btnRegister").attr("disabled", true);
 30             } else {
 31                 $("#btnRegister").removeAttr("disabled");
 32                 //$("#btnRegister").attr("disabled", false);
 33             }
 34         })
 35         $("#btnRegister").click(function () {
 36             if ($("#Agreest").checked == false) {
 37                 alert("请认真阅读用户注册协议!");
 38                 return;
 39             }
 40             var vc = $("#verificationcode").val();
 41             $.ajax({
 42                 type: "POST",
 43                 url: "/VerificationCode/Register",
 44                 data: $("#FormRegister").serialize(),
 45                 success: function (data) {
 46                     alert(data);
 47                     $("#verificationcodeimg").attr("src", "@Url.Action("VerificationCode")?" + new Date());
 48                 }
 49             });
 50         });
 51         $("#verificationcodeimg").click(function () {
 52             $("#verificationcodeimg").attr("src", "@Url.Action("VerificationCode")?" + new Date());
 53         });
 54     });
 55 
 56 </script>
 57 <form action="/VerificationCode/Register" method="post" id="FormRegister">
 58     <table class="td">
 59         <tr>
 60             <td></td>
 61             <td>用户注册</td>
 62             <td></td>
 63         </tr>
 64         <tr>
 65             <td>账号:</td>
 66             <td>
 67                 <input type="text" class="txt" value="" name="AccountNumber" id="AccountNumber">
 68             </td>
 69             <td></td>
 70         </tr>
 71         <tr>
 72             <td>密码:</td>
 73             <td>
 74                 <input type="text" class="txt" value="" name="Password" id="Password">
 75             </td>
 76             <td></td>
 77         </tr>
 78         <tr>
 79             <td>确认密码:</td>
 80             <td>
 81                 <input type="text" class="txt" value="" name="ConfirmPassword" id="ConfirmPassword">
 82             </td>
 83             <td></td>
 84         </tr>
 85         <tr>
 86             <td>验证码:</td>
 87             <td>
 88                 <input type="text" class="txt" value="" name="verificationcode" id="verificationcode">
 89             </td>
 90             <td>
 91                 <img id="verificationcodeimg" class="img" title = "点击刷新" src = "@Url.Action("VerificationCode")" style="cursor:pointer"/></td>
 92         </tr>
 93         <tr>
 94             <td colspan="2">
 95                 <input id="Agreest" type="checkbox" checked="checked" />我同意<a href="#">《用户注册协议》</a>
 96             </td>
 97             <td></td>
 98         </tr>
 99         <tr>
100             <td></td>
101             <td>
102                 <input type="button" value="注册" id="btnRegister" class="btn" />
103             </td>
104             <td></td>
105         </tr>
106     </table>
107 </form>
Index

 实例效果图,如下:

C#生成简单验证码第7张

作者:长毛象
本文版权归作者和博客园共有,个人学习成果,请多多指教,欢迎转载,请保留原文链接

免责声明:文章转载自《C#生成简单验证码》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇RAC集群常用管理命令OracleERP表结构INV模块下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

Java使用JaxWsDynamicClientFactory和HttpURLConnection两种方式调取webservice的接口

方式1.代理类工厂的方式,需要拿到对方的接口 try { // 接口地址 // 代理工厂 JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean(); // 设置代理地址 wsdlAddress: WSDL地址(http://localhost...

用C#实现Web代理服务器3

  9.创建Proxy类中的Run方法。Run方法是Proxy类中唯一的方法。其功能是从客户端接收HTTP请求,并传送到Web服务器,然后从Web服务器接收反馈来的数据,并传送到客户端。为了实现这二个不同方面的数据传送,Run方法中是通过两个Socket实例来实现的。在编写Run方法的时候,要注意下面两点:   (1)由于HTTP建立于TCP协议之上,所以...

.net微信公众号开发——快速入门【转载】

最近在学习微信公众号开发,将学习的成果做成了一个类库,方便重复使用。 现在微信公众号多如牛毛,开发微信的高手可以直接无视这个系列的文章了。 使用该类库的流程及寥寥数行代码得到的结果如下。 本文的源代码主要在:http://git.oschina.net/xrwang2/xrwang.weixin.PublicAccount/blob/master/xr...

Jackson 框架,轻易转换JSON

Jackson能够轻松的将Java对象转换成json对象和xml文档。相同也能够将json、xml转换成Java对象。 前面有介绍过json-lib这个框架,在线博文:http://www.cnblogs.com/hoojo/archive/2011/04/21/2023805.html 相比json-lib框架,Jackson所依赖的jar包较少。简...

【转】Asp.Net MVC及Web API框架配置会碰到的几个问题及解决方案

前言 刚开始创建MVC与Web API的混合项目时,碰到好多问题,今天拿出来跟大家一起分享下。有朋友私信我问项目的分层及文件夹结构在我的第一篇博客中没说清楚,那么接下来我就准备从这些文件怎么分文件夹说起。问题大概有以下几点: 1、项目层的文件夹结构       2、解决MVC的Controller和Web API的Controller类名不能相同的问题  ...

Go语言读取网上Json格式的天气预报数据例子

天气预报接口使用的是:http://www.weather.com.cn/data/sk/101010100.html 这里的Json数据如下:   {        "weatherinfo": {               "city": "北京",               "cityid": "101010100",             ...