• C#生成简单验证码


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

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

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

     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

     后台控制器代码,如下:

     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

     前台页面代码,如下:

      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

     实例效果图,如下:

  • 相关阅读:
    【SpringMVC】数据校验时,抛出javax.validation.UnexpectedTypeException: HV000030: No validator could be found for type: java.util.Date.
    【SpringMVC】添加操作时返回400
    【c#】 使用Directory.GetFiles获取局域网中任意电脑指定文件夹下的文件
    【opencv】Java实现opencv 调用本地摄像头,实现人脸识别、人形识别、人眼识别
    【opencv】Java实现的opencv3.x版本后Highhui报错
    【opencv】Java+eclipse+opencv 环境搭建 helloword入门demo
    【微信小程序】--小程序中循环遍历(包括js中遍历和wxml中的遍历)
    【微信小程序】--bindtap参数传递,配合wx.previewImage实现多张缩略图预览
    linux命令:tail
    system()
  • 原文地址:https://www.cnblogs.com/xiangyisheng/p/6429771.html
Copyright © 2020-2023  润新知