zoukankan      html  css  js  c++  java
  • C#——验证码图片生成及.net mvc登录验证码实现

    1.验证码图片生成类

        /// <summary>
        /// 生成验证码图片类
        /// </summary>
        public class VerifyCodeHelper
        {
            public static Bitmap CreateVerifyCode(out string code)
            {
                //建立Bitmap对象,绘图
                Bitmap bitmap = new Bitmap(200, 60);
                Graphics graph = Graphics.FromImage(bitmap);
                graph.FillRectangle(new SolidBrush(Color.White), 0, 0, 200, 60);
                Font font = new Font(FontFamily.GenericSerif, 48, FontStyle.Bold, GraphicsUnit.Pixel);
                Random r = new Random();
                string letters = "ABCDEFGHIJKLMNPQRSTUVWXYZ0123456789";
    
                StringBuilder sb = new StringBuilder();
    
                //添加随机的五个字母
                for (int x = 0; x < 5; x++)
                {
                    string letter = letters.Substring(r.Next(0, letters.Length - 1), 1);
                    sb.Append(letter);
                    graph.DrawString(letter, font, new SolidBrush(Color.Black), x * 38, r.Next(0, 15));
                }
                code = sb.ToString();
    
                //混淆背景
                Pen linePen = new Pen(new SolidBrush(Color.Black), 2);
                for (int x = 0; x < 6; x++)
                    graph.DrawLine(linePen, new Point(r.Next(0, 199), r.Next(0, 59)), new Point(r.Next(0, 199), r.Next(0, 59)));
                return bitmap;
            }
        }

    使用上述类时需要添加相关引用

    2.后台controller的提供验证码图片的action方法

            /// <summary>
            /// 提供验证码
            /// </summary>
            /// <returns></returns>
            public ActionResult VerifyCode()
            {
                string verifyCode = string.Empty;
                Bitmap bitmap = VerifyCodeHelper.CreateVerifyCode(out verifyCode);
    
                #region 缓存Key 
                Cache cache = new Cache();
                // 先用当前类的全名称拼接上字符串 “verifyCode” 作为缓存的key
                var verifyCodeKey = $"{this.GetType().FullName}_verifyCode";
                cache.Remove(verifyCodeKey);
                cache.Insert(verifyCodeKey, verifyCode);
                #endregion
    
                MemoryStream memory = new MemoryStream();
                bitmap.Save(memory, ImageFormat.Gif);
                return File(memory.ToArray(), "image/gif");
            }

    这里使用了cache来存储验证码的值以便在登录方法中与用户输入的验证码做对比,cache可以在缓存,它可以在用户登录方法中将相应的值取出来

    3.后台处理登录请求的action方法(验证码比对)

            public ActionResult Login(string verifyCode)
            {
                    // 第一步检验验证码
                    // 从缓存获取验证码作为校验基准  
                    // 先用当前类的全名称拼接上字符串 “verifyCode” 作为缓存的key
                    Cache cache = new Cache();
                    var verifyCodeKey = $"{this.GetType().FullName}_verifyCode";
                    object cacheobj = cache.Get(verifyCodeKey);
                    if (cacheobj == null)
                    {
                        return Json(new
                        {
                            Success = false,
                            Message = "验证码已失效"
                        });
                    }//不区分大小写比较验证码是否正确
                    else if (!(cacheobj.ToString().Equals(verifyCode, StringComparison.CurrentCultureIgnoreCase)))
                    {
                        return Json(new
                        {
                            Success = false,
                            Message = "验证码错误"
                        });
                    }
                    cache.Remove(verifyCodeKey);
            //...接下来再进行账号密码比对等登录操作
    
            }

    4.前端cshtml相关代码(注意要有对应的action返回view与其对应)

    @{
        Layout = null;
    }
    
    <!DOCTYPE html>
    
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Test</title>
    </head>
    <body>
        <div>
            <img id="verifycode" style="height: 36px;
                     108px;
                    margin-left: -15px;
                    margin-top: -8px;
        cursor: pointer;" src="@Url.Action("VerifyCode")" />
        </div>
    </body>
    </html>

    验证码功能的具体实现:cshtml页面,点击验证码时切换新的。

    除了src调用了@Url.Action("VerifyCode"),还要加一个onclick事件,里面调用 @Url.Content("~/Login/VerifyCode")?time='+new Date().getTime()。
    <div>
        <input name="validatecode" type="text" id="validatecode"class="loginvalidatecode ipt" placeholder="请输入验证码">
           <img id="verifycode" style="height: 36px; 108px;margin-left: 15px;cursor: pointer;" 
    src
    ="@Url.Action("VerifyCode")" onclick="this.src='@Url.Content("~/Login/VerifyCode")?time='+new Date().getTime()"
    title
    ="看不清?换一张" alt="看不清?换一张" /> </div>
    
    
    
  • 相关阅读:
    微信小程序开发(十)获取手机的经纬度
    微信小程序开发(九)获取手机连接的wifi信息
    微信小程序开发(八)获取手机ip地址
    微信小程序开发(七)获取手机网络类型
    微信小程序开发(六)获取手机信息
    关于JPype报FileNotFoundError: [Errno 2] No such file or directory: '/usr/lib/jvm'错误的解决
    微信小程序开发(五)数据绑定
    微信小程序开发(四)页面跳转
    微信小程序开发(三)点击事件
    微信小程序开发(二)创建一个小程序页面
  • 原文地址:https://www.cnblogs.com/supermarrio/p/13262416.html
Copyright © 2011-2022 走看看