吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 7443|回复: 11
收起左侧

[其他转载] ASP.NET MVC实现图片验证码的功能

[复制链接]
Naylor 发表于 2017-6-14 15:18
本帖最后由 Naylor 于 2017-6-14 15:37 编辑

一、首先:
       本文的关键代码源自CSDN博客,原文链接:http://blog.csdn.net/wupd2014/article/details/53232448
       图片验证码是一个Web项目不可或缺的功能,该博主封装的代码也很好理解,特借用过来。

       效果图:

123.png

二、项目结构及关键代码:


9_SP7MT7AUE4J_)_U[O4PI7.png



       1:publicclass文件夹是一个项目公共类文件夹,里面的生成验证码的代码如下:
[Asm] 纯文本查看 复制代码
 public class VerifyCode
    {
        public byte[] GetVerifyCode()
        {
            int codeW = 80;
            int codeH = 30;
            int fontSize = 16;
            string chkCode = string.Empty;
            Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.DarkBlue };
            string[] font = { "Times New Roman" };
            char[] character = { '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'd', 'e', 'f', 'h', 'k', 'm', 'n', 'r', 'x', 'y', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' };
            //生成验证码字符串
            Random rnd = new Random();
            for (int i = 0; i < 4; i++)
            {
                chkCode += character[rnd.Next(character.Length)];
            }
            //写入Session用于验证码校验,可以对校验码进行加密,提高安全性
            System.Web.HttpContext.Current.Session["verifyCode"] = chkCode;
            //创建画布
            Bitmap bmp = new Bitmap(codeW, codeH-3);
            Graphics g = Graphics.FromImage(bmp);
            g.Clear(Color.White);

            //画噪线
            for (int i = 0; i < 3; i++)
            {
                int x1 = rnd.Next(codeW);
                int y1 = rnd.Next(codeH);
                int x2 = rnd.Next(codeW);
                int y2 = rnd.Next(codeH);

                Color clr = color[rnd.Next(color.Length)];
                g.DrawLine(new Pen(clr), x1, y1, x2, y2);
            }
            //画验证码
            for (int i = 0; i < chkCode.Length; i++)
            {
                string fnt = font[rnd.Next(font.Length)];
                Font ft = new Font(fnt, fontSize);
                Color clr = color[rnd.Next(color.Length)];
                g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 18, (float)0);
            }
            //将验证码写入图片内存流中,以image/png格式输出
            MemoryStream ms = new MemoryStream();
            try
            {
                bmp.Save(ms, ImageFormat.Png);
                return ms.ToArray();
            }
            catch (Exception ex)
            {
                return null;
            }
            finally
            {
                g.Dispose();
                bmp.Dispose();
                ms.Dispose();
            }
        }




      2:控制器层代码:IdentifyingCode方法返回一个视图,CreateVerifyCode方法调用VerifyCode类中的GetVerifyCode方法获取byte数组(即图片),CheckVerifyCode方法验证用户输入的代码是否是验证码,供前台页面表单提交时候调用。关键代码如下:



[Asm] 纯文本查看 复制代码
     public ActionResult IdentifyingCode()
        {
            return View();
        }

        public ActionResult CreateVerifyCode()
        {
            VerifyCode vc = new PublicClass.VerifyCode();
            byte[] result = vc.GetVerifyCode();            
            return File(result, "image/jpeg jpeg jpg jpe");
        }

        public string CheckVerifyCode(string thecode)
        {
            string result = "";
            string sessioncode = Session["verifyCode"].ToString();
            string thecodeX = thecode.ToLower();
            string sessioncodeX = sessioncode.ToLower();
            if (thecodeX == sessioncodeX)
            {
                result = "ok";
            }
            else
            {
                result = "no";
            }
            return result;
        }



      
3:视图层代码:img标签的src属性初始给“/Demo/CreateVerifyCode”,用于获取验证码图片,在图片的点击事件中,改变当前图片的src属性,让其重新去从服务器获取图片,在提交按钮的点击事件中获取用户输入的代码传递到后台作验证。关键代码如下:


[Asm] 纯文本查看 复制代码
@{
    ViewBag.Title = "";
    Layout = "~/Views/Shared/_Layoutcml.cshtml";
}


<h2>.NET MVC验证码</h2>

<img src="/Demo/CreateVerifyCode" id="verifycode" alt="验证码获取失败" title="验证码" style="border:1px solid black;" />
<input type="text" value="" id="inputcode" />
<br />
<input type="button" value="提交" id="ok" />
<script>
    $(function () {
        $("#ok").click(function (e) {
            debugger
            var thecode = $("#inputcode").val();
            $.ajax({
                url: "/Demo/CheckVerifyCode",
                type: "Get",
                data: { thecode: thecode },
                success: function (data) {
                    if (data == "ok") {
                        alert("验证码输入正确。");
                    } else {
                        alert("验证码输入错误。");
                    }
                },
                error: function () { }
            })
        })

        $("#verifycode").click(function (e) {
            debugger
            //TODO:这里,可在客户端作一个简单过滤,防止客户端恶意请求服务器。当然,最好的操作方式是在服务器端也做这个操作
            this.src = "/Demo/CreateVerifyCode/" + Math.floor(Math.random() * 10000);
        })
    })

</script>



三、释及注意点:


免费评分

参与人数 3吾爱币 +2 热心值 +3 收起 理由
雫Hao洋洋 + 1 热心回复!
吴兜兜 + 1 + 1 鼓励转贴优秀软件安全工具和文档!
我是耐寒马 + 1 + 1 热心回复!

查看全部评分

本帖被以下淘专辑推荐:

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

风予 发表于 2017-6-15 16:35
感谢分享,先收藏了········
平淡哥 发表于 2017-6-15 21:56
574261766 发表于 2017-6-17 22:54
 楼主| Naylor 发表于 2017-6-19 18:10

额  哪里看不懂?
bobliu 发表于 2017-7-29 16:50
额 还是挺实用的 不错
潘天淼 发表于 2017-8-3 08:54
Mark一下。感谢分享
天下有道 发表于 2017-8-22 21:29
mvc学习,路由是比较难理解的
吸金瓶子 发表于 2017-11-12 20:14
马克一下,厉害了大佬
maqingyao 发表于 2017-11-22 11:20
不错,,,学习了。。。。。。。
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止灌水或回复与主题无关内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-3-28 23:25

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表