C# Web 端添加登录验证码

来源:互联网 发布:sql 删除表中行 编辑:程序博客网 时间:2024/05/21 19:23

        写在前面:最近做的学校项目需要添加登录验证码,而我又是一个刚转专业到计算机的学渣,所以对添加 Web 端验证码一窍不通。不过在请教了同学,以及在网上找各种资料,经过自己的测试,算是加了一个简单的登录验证码。下面把添加验证码的过程记录一下,以便以后自己学习改进,也可以让跟我一样的小白同学省点找资料的功夫。


1) 首先,我们需要从网上找一个生产验证码图片的类(主要是我不会自己写大哭)。看本篇文章的同学就不用找了,我直接把代码贴在下面,具体的注释,源码的作者已经都写了,大家都能看明白怎么用,有机会再仔细研究下吧。


using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;

namespace TestSecurityCode01.App_Start
{
    public class SecurityCode
    {
        /// <summary>
        /// 生成随机的字符串
        /// </summary>
        /// <param name="codeCount">验证码长度</param>
        /// <returns></returns>
        public string CreateRandomCode(int codeCount)
        {
            string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,a,b,c,d,e,f,g,h,i,  g,k,l,m,n,o,p,q,r,F,G,H,I,G,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,s,t,u,v,w,x,y,z";
            string[] allCharArray = allChar.Split(',');
            string randomCode = "";
            int temp = -1;
            Random rand = new Random();
            for (int i = 0; i < codeCount; i++)
            {
                if (temp != -1)
                {
                    rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
                }
                int t = rand.Next(35);
                if (temp == t)
                {
                    return CreateRandomCode(codeCount);
                }
                temp = t;
                randomCode += allCharArray[t];
            }
            return randomCode;
        }

        /// <summary>
        /// 创建验证码图片
        /// </summary>
        /// <param name="validateCode">验证码无干扰字符串</param>
        /// <returns></returns>
        public byte[] CreateValidateGraphic(string validateCode)
        {
            Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 22.0), 40);
            Graphics g = Graphics.FromImage(image);
            try
            {
                //生成随机生成器
                Random random = new Random();
                //清空图片背景色
                g.Clear(Color.White);
                //画图片的干扰线
                for (int i = 0; i < 25; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);
                    g.DrawLine(new Pen(Color.Silver), x1, x2, y1, y2);
                }
                Font font = new Font("Arial", 20, (FontStyle.Bold | FontStyle.Italic));
                LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue,Color.DarkRed, 1.2f, true);
                g.DrawString(validateCode, font, brush, 3, 2);


                //画图片的前景干扰线
                for (int i = 0; i < 100; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);
                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }
                //画图片的边框线
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);

                //保存图片数据
                MemoryStream stream = new MemoryStream();
                image.Save(stream, ImageFormat.Jpeg);

                //输出图片流
                return stream.ToArray();
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }
    }
}


然后,我们需要建一个类,名字就叫 SecurityCode ,把这个类放在一个你能找到的文件夹下,我放到了这里(别问为什么放这里,我只是为了好找)


2)我们需要在 控制器里添加一个生产验证码图片的方法,我这里是添加到了HomeController。首先来张图:


下面贴上代码(不贴代码,帖子还有什么意义?)


           static string  securityCode_input = "";
        public ActionResult GetSecurityCode()
        {
            SecurityCode code = new SecurityCode();
            securityCode_input = code.CreateRandomCode(4);
            byte[] buf = code.CreateValidateGraphic(securityCode_input);
            //securityCode_input = buf.ToString();
            return File(buf, "image/Jpeg");
        }


注意 securityCode_input这个变量应该是静态的,否则每次进入控制器,该变量都会重置。这个变量就是随机生成的字符串验证码。  大家可以调试一遍走一走。(这段代码就是HomeController 里面的代码,而 HomeController  的视图就是我们需要添加验证码的页面,在本文里是 Index.cshtml 


3)下面就是在前台页面调用该验证码了,这里有两种方法,个人比较推荐第二种,虽然第二种有时候会出异常。。。照例先来截图:

方法一:



下面贴上代码:

<script type="text/javascript">
    window.onload = function () {
        $("#secImg").click(function () {
            ///注意后面的flag是必须的,如果不添加会导致部分浏览器不能刷新验证码
            $("#secImg").attr("src", "GetSecurityCode?flag=" + Math.random());
        });
    }
</script>


<form action="CheckSecurityCode" method="post">
<div style="width:100px;height:80px;margin:50px auto">
    <input type="text" id="securityCode" name="securityCode" required>
    <p><img src="~/Home/GetSecurityCode" id="secImg" title="换一张" /></p>
    @*如果不添加 ~/Home/ 则有时会出现404错误,Home 代表控制器的名称,也就是HomeController*@
</div>
    <p><input type="submit"> </p>
</form>



方法二:


下面贴上代码:

<script type="text/javascript">
    window.onload = function () {    
        $("#secImg").click();      
    }
</script>


<form action="~/Home/CheckSecurityCode" method="post">
<div style="width:100px;height:80px;margin:50px auto">
    <input type="text" id="securityCode" name="securityCode" required>
    <p><img onclick="this.src= document.location.protocol + '/Home/GetSecurityCode?flag=' + Math.random(); " id="secImg" title="换一张" /></p>
     @* 注意后面的flag是必须的,如果不添加会导致部分浏览器不能刷新验证码 *@
</div>

<p><input type="submit"> </p>
</form>


结束!!!!!!!!!!!!!!!!!!!


下面来张运行成功截图:






写在后面:大家发现错误一定帮我指出,谢谢!


原创粉丝点击