码迷,mamicode.com
首页 > Windows程序 > 详细

C#——验证码图片生成及.net mvc登录验证码实现

时间:2020-07-07 19:40:52      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:字母   用户   页面   相关   大小   type   val   ice   mil   

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;
                width: 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;width: 108px;margin-left: 15px;cursor: pointer;" 
src
="@Url.Action("VerifyCode")" onclick="this.src=‘@Url.Content("~/Login/VerifyCode")?time=‘+new Date().getTime()"
title
="看不清?换一张" alt="看不清?换一张" /> </div>

 


 

C#——验证码图片生成及.net mvc登录验证码实现

标签:字母   用户   页面   相关   大小   type   val   ice   mil   

原文地址:https://www.cnblogs.com/supermarrio/p/13262416.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!