一、先看一下实现的效果:
二、具体实现
1、封装的helper类,拿来用就行
public class VerificationCodeHelper { private static Color BackColor = Color.White; private static int Width = 62; private static int Height = 21; private Random _random; // private string _code; private int _brushNameIndex; public byte[] GetVCode(string codeStr) { _random = new Random(); using (Bitmap img = new Bitmap(Width, Height)) { // _code = GetRandomCode(); // System.Web.HttpContext.Current.Session["vcode"] = _code; using (Graphics g = Graphics.FromImage(img)) { g.Clear(Color.White);//绘画背景颜色 Paint_Text(g, codeStr);// 绘画文字 // g.DrawString(strCode, new Font("微软雅黑", 15), Brushes.Blue, new PointF(5, 2));// 绘画文字 Paint_TextStain(img);// 绘画噪音点 g.DrawRectangle(Pens.DarkGray, 0, 0, Width - 1, Height - 1);//绘画边框 using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { //将图片 保存到内存流中 img.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); //将内存流 里的 数据 转成 byte 数组 返回 return ms.ToArray(); } } } } /// <summary> /// 绘画文字 /// </summary> /// <param name="g"></param> private void Paint_Text(Graphics g, string code) { g.DrawString(code, GetFont(), GetBrush(), 3, 1); } /// <summary> /// 绘画文字噪音点 /// </summary> /// <param name="g"></param> private void Paint_TextStain(Bitmap b) { string[] BrushName = new string[] { "OliveDrab", "ForestGreen", "DarkCyan", "LightSlateGray", "RoyalBlue", "SlateBlue", "DarkViolet", "MediumVioletRed", "IndianRed", "Firebrick", "Chocolate", "Peru", " enrod" }; for (int n = 0; n < 30; n++) { int x = _random.Next(Width); int y = _random.Next(Height); b.SetPixel(x, y, Color.FromName(BrushName[_brushNameIndex])); } } /// <summary> /// 随机取一个字体 /// </summary> /// <returns></returns> private Font GetFont() { string[] FontItems = new string[]{ "Arial", "Helvetica", "Geneva", "sans-serif", "Verdana" }; int fontIndex = _random.Next(0, FontItems.Length); FontStyle fontStyle = GetFontStyle(_random.Next(0, 2)); return new Font(FontItems[fontIndex], 12, fontStyle); } /**/ /**/ /**/ /// <summary> /// 随机取一个笔刷 /// </summary> /// <returns></returns> private Brush GetBrush() { Brush[] BrushItems = new Brush[]{ Brushes.OliveDrab, Brushes.ForestGreen, Brushes.DarkCyan, Brushes.LightSlateGray, Brushes.RoyalBlue, Brushes.SlateBlue, Brushes.DarkViolet, Brushes.MediumVioletRed, Brushes.IndianRed, Brushes.Firebrick, Brushes.Chocolate, Brushes.Peru, Brushes.Goldenrod }; int brushIndex = _random.Next(0, BrushItems.Length); _brushNameIndex = brushIndex; return BrushItems[brushIndex]; } /// <summary> /// 绘画背景颜色 /// </summary> /// <param name="g"></param> private void Paint_Background(Graphics g) { g.Clear(BackColor); } /**/ /**/ /**/ /// <summary> /// 取一个字体的样式 /// </summary> /// <param name="index"></param> /// <returns></returns> private FontStyle GetFontStyle(int index) { switch (index) { case 0: return FontStyle.Bold; case 1: return FontStyle.Italic; default: return FontStyle.Regular; } } /// <summary> /// 取得一个 4 位的随机码 /// </summary> /// <returns></returns> public string GetRandomCode() { return Guid.NewGuid().ToString().Substring(0, 5); } }
2、HTML页面部分:
<div class="row cl"> <div class="formControls col-xs-8 col-xs-offset-3"> <input class="input-text size-L" type="text" placeholder="验证码" onblur="if(this.value==''){this.value='验证码:'}" onclick="if(this.value=='验证码:'){this.value='';}" value="验证码:" style="150px;"> <img id="checkloing" src="/Login/VCode" width="70" height="40" class="loginFormCheckCodeImg" onclick="reloadcode('/Login/VCode')" title="看不清,换一张" /> </div> </div>
//刷新验证码 js脚本代码 function reloadcode(srcStr) { document.getElementById("checkloing").src = srcStr + "?rand=" + Math.random(); } var checkInfo = ""; //检查数据 function Check() { checkInfo = ""; //检查不能为空的数据 $("input[Require='True']").each(function (i) { var tmpName = $(this).attr("name"); var strVal = $(this).val(); strVal = strVal.replace(/s/g, "") if (!strVal) checkInfo += $(this).attr("placeholder") + "不能为空。<br/>"; }); if (checkInfo) return false; return true; } $(function () { $("#btnLogin").click(function () { var ii = layer.load(); if (!Check()) { layer.close(ii); layer.msg('' + checkInfo, function () { }); return; } $("#loadingDiv").show(); $.ajax({ url: "/Home/Index", type: "post", data: "userName=" + $("#tbUserName").val() + "&pwd=" + $("#tbPWD").val() + "&code=" + $("#checkInput").val(), success: function (data) { debugger; if (data.Result == "0") { layer.close(ii); layer.msg('' + data.MSG); return; } else if (data.Result == "1") { layer.close(ii); window.location.href = "/Home/Index"; } }, error: function (data) { layer.close(ii); layer.msg('' + data.MSG); } }); }); });
MVC控制器提供验证码的方法:
[AllowAnonymous]//跳过登陆验证 public ActionResult VCode() { VerificationCodeHelper vcode = new VerificationCodeHelper(); string codeStr = vcode.GetRandomCode(); if (!string.IsNullOrEmpty(codeStr)) { byte[] arrImg = vcode.GetVCode(codeStr); Session["code"] = codeStr; return File(arrImg, "image/gif"); } else { return RedirectToAction("/Login/VCode?rand=" + Guid.NewGuid().ToString().Substring(1, 10), "image/jpeg"); } }
验证页面数据的方法:
[HttpPost] public ActionResult Index(string userName, string pwd) { try { string vccode = Request.Form["code"]; if (string.IsNullOrEmpty(vccode)) return Json(new { Result = "0", MSG = "请填写验证码" }); else { if (Session["code"] == null) return Json(new { Result = "0", MSG = "验证码已过期,请点击刷新验证码" }); string str = Session["code"].ToString(); str = str.ToLower(); vccode = vccode.ToLower(); if (str != vccode) return Json(new { Result = "0", MSG = "验证码填写错误!" }); else { Session["code"] = null; } if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(pwd)) { return Json(new { Result = "0", MSG = "用户或密码没有填写" }); } //查询此用户 #region 查询此用户 List<Models.MySqlUser> adminml = new List<Models.MySqlUser>(); Models.MySqlUser admin = new Models.MySqlUser(); adminml = IBCodeBll.GetModelList(userName.Trim()); if (adminml.Count > 0) { if (!adminml[0].password.ToLower().Equals(Maticsoft.Common.DEncrypt.DESEncrypt.Encrypt2(pwd.Trim()).ToLower())) { return Json(new { Result = "0", MSG = "密码错误!" }); } } else { return Json(new { Result = "0", MSG = "用户不在在!" }); } #endregion Session["UserName"] = userName.Trim().ToString(); return Json(new { Result = "1", MSG = "登录成功!" }); } } catch (Exception ex) { return Json(new { Result = "0", MSG = ex.Message }); } }
参考资料:https://www.cnblogs.com/zhangxiaoyong/p/6210953.html