一般处理程序生成简单的图片验证码并通过html验证用户输入的验证码是否正确

时间:2022-07-10 06:39:01

              一般处理程序生成简单的图片验证码并通过html验证用户输入的验证码是否正确

      最近没事研究了下验证码的的动态生成及通过cookie实现HTML页面对用户输入的验证码的校验,简要如下:

1、写了一个简单的验证码后台生成页面,代码如下:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Web;

using System.Drawing.Imaging;

namespace Asp.Net的学习
{
    /// <summary>
    /// ValidateImg 的摘要说明
    /// </summary>
    public class ValidateImg : IHttpHandler
    {
        //需要随机生成的字符
        char[] chars = null;
        Random ran = new Random();
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "image/jpeg";
            //实例化需要随机产生的字符数组
            chars = new char[10] { 'a','B','D','f','R','I','L','1','7','9'};

//获得随机生成的字符串
            string s = GetRandomStr(5);
            //定义一个画布对象,来实现验证码图片的画画
            using (Image img = new Bitmap(90, 35))
            {
                using (Graphics g = Graphics.FromImage(img))
                {
                    //清除白色背景
                    g.Clear(Color.White);
                    //画一个边框
                    g.DrawRectangle(new Pen(Brushes.Black),new Rectangle(0,0,img.Width-1,img.Height-1));
                    //画干扰线或者点

g.DrawString(s, new Font("微软雅黑", 14), Brushes.Red, 2, 5);
                    //画干扰线
                    DrawGanRao(g, 150, img);
                   
                }

//将img图片画到页面上来,以jepg的格式画
                img.Save(context.Response.OutputStream, ImageFormat.Jpeg);

HttpCookie cookie = new HttpCookie("code", s);
                context.Response.Cookies.Add(cookie);
                context.Response.Write("testaa");
                //测试cookie
                //context.Response.Cookies.Add(new HttpCookie("test","wahah"));
            }

}

#region 产生随机字符串
        private string GetRandomStr(int count)
        {
            StringBuilder sb = new StringBuilder(5);
            for (int i = 0; i < count; i++)
            {
                //得到随机数
                int index = ran.Next(chars.Length);
                sb.Append(chars[index]);
            }

return sb.ToString();
        }
        #endregion

#region 画干扰点
        /// <summary>
        /// 画干扰点
        /// </summary>
        /// <param name="g">画布</param>
        /// <param name="count">干扰点的数目</param>
        private void DrawGanRao(Graphics g,int count,Image img)
        {
            for (int i = 0; i < count; i++)
            {
                Point p1 = new Point(ran.Next(img.Width-1), ran.Next(img.Height-1));
                Point p2 = new Point(p1.X-3,p1.Y-3);

g.DrawLine(new Pen(Brushes.Blue), p1, p2);
            }
        }
        #endregion

public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

2、前台的html代码如下:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>登陆界面</title>
    <script type="text/javascript">
        window.onload = function () {
            //加载cookie
            loadCookie();

//加载提交事件的方法
            getDom("btnLogin").onclick = function () {
                //重新加载cookie
                loadCookie();

//获取图片验证码
                var hidCode = getDom("hidCode").value.toLowerCase();
                //判断当前用户输入的验证码和图片中的验证码是否一致,不一致则提示
                var validCode = getDom("txtValidCode").value.toLowerCase();
                if (validCode != hidCode) {
                    alert("验证码错误!请重新输入!")
                }
                else {
                    alert("验证码输入正确!");
                }
            }

//刷新验证码第一版本(采用url地址随时变化来刷新)
            getDom("imgCode").onclick = function () {
                this.src = "ValidateImg.ashx?time=" + new Date().toString();
                //注意加载cookie页面不能放在这个位置,否则获取到的后台的验证码字符串就不是最新的了
                //loadCookie();
            }
        }

function changeImg()
        {
            getDom("imgCode").src = "ValidateImg.ashx?time=" + new Date().toString();
        }

//获得当前页面的cookie并加载到页面的隐藏域中
        function loadCookie()
        {
            //获得当前cookie键值对的形式
            var cookies = document.cookie;
            var arrCookies = cookies.split(';');
            for (var i = 0; i < arrCookies.length; i++) {
                //遍历cookies
                var arr = arrCookies[i].split('=');
                if (arr[0] == "code") {
                    //将当前找到的cookie里面的验证码的值加到隐藏域中
                    getDom("hidCode").value = arr[1];
                }

}
        }

//获取dom的方法
        function getDom(domId)
        {
            return document.getElementById(domId);
        }
    </script>
</head>
<body>
    <form>
        <table>
            <tr>
                <td>用户名:</td>
                <td><input type="text" name="txtUserName" /></td>
                <td></td>
            </tr>
             <tr>
                <td>密&nbsp;&nbsp;&nbsp;&nbsp;码:</td>
                <td><input type="password" name="txtPwd" /></td>
                  <td></td>
            </tr>
            <tr>
                <td>验证码:</td>
                <td><input type="text" name="txtValidCode" /></td>
                <td><img src="ValidateImg.ashx" alt="单击刷新" id="imgCode" /><a href="javascript:changeImg();" id="reflush" >单击刷新</a></td>
            </tr>
            <tr>
                <td colspan="3">
                    <input type="button" value="登陆" id="btnLogin" />
                </td>
            </tr>
        </table>
        <input type="hidden" id="hidCode" />
    </form>
</body>
</html>

以上是用js实现的验证,菜鸟学习用哈哈