一个简单的验证码的例子

来源:互联网 发布:淘宝店铺怎么注销重开 编辑:程序博客网 时间:2024/05/17 08:06

 下面是一个简单的实现验证码的例子,包括生成验证码,JavaScript异步调用验证,超时,等,代码很简单,稍微看看就可以明白

在网上搜了很多例子,总结如下

生成随机图片,这个是在网上找的源码,新建一个网页,在page_load里加如下代码,Identity是验证时session的关键字Key,我取的是远程IP和时间戳,这样在验证的时候保证唯一性

 protected void Page_Load(object sender, EventArgs e)
        {
            string chkCode = string.Empty;
            //颜色列表,用于验证码、噪线、噪点
            Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue };
            //字体列表,用于验证码
            string[] font = { "Times New Roman", "MS Mincho", "Book Antiqua", "Gungsuh", "PMingLiU", "Impact" };
            //验证码的字符集,去掉了一些容易混淆的字符
            char[] character = { '2', '3', '4', '5', '6', '8', '9', '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[Identity] = chkCode;

            Response.Cookies.Add(new HttpCookie(Identity, chkCode));
            Bitmap bmp = new Bitmap(100, 40);
            Graphics g = Graphics.FromImage(bmp);
            g.Clear(Color.White);
            //画噪线
            for (int i = 0; i < 10; i++)
            {
                int x1 = rnd.Next(100);
                int y1 = rnd.Next(40);
                int x2 = rnd.Next(100);
                int y2 = rnd.Next(40);
                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, 18);
                Color clr = color[rnd.Next(color.Length)];
                g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 20 + 8, (float)8);
            }
            //画噪点
            for (int i = 0; i < 100; i++)
            {
                int x = rnd.Next(bmp.Width);
                int y = rnd.Next(bmp.Height);
                Color clr = color[rnd.Next(color.Length)];
                bmp.SetPixel(x, y, clr);
            }
            //清除该页输出缓存,设置该页无缓存
            Response.Buffer = true;
            Response.ExpiresAbsolute = System.DateTime.Now.AddMilliseconds(0);
            Response.Expires = 0;
            Response.CacheControl = "no-cache";
            Response.AppendHeader("Pragma", "No-Cache");
            //将验证码图片写入内存流,并将其以 "image/Png" 格式输出
            MemoryStream ms = new MemoryStream();
            try
            {
                bmp.Save(ms, ImageFormat.Png);
                Response.ClearContent();
                Response.ContentType = "image/Png";
                Response.BinaryWrite(ms.ToArray());
            }
            finally
            {
                //显式释放资源
                bmp.Dispose();
                g.Dispose();
            }
        }

调用这个随机码

再新建一个页面,在页面上加一个image控件,通过JavaScript来指定图片的src为刚才生成随机码的页面,加一个输入框,输入验证码,加一个linkbutton,当看不清的时候换一张,放一个button,当单击的时候验证输入是否合法,

<form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td>
                    <asp:TextBox ID="txtCode" runat="server"></asp:TextBox>
                    <asp:Image ID="imgURL"  runat="server" />
                    <asp:LinkButton ID="LinkButton1" runat="server" OnClientClick="LoadPage();return false">看不清,换一张</asp:LinkButton>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="Test();return false" />
                </td>
            </tr>
        </table>
    </div>
    </form>
       <script type="text/javascript" language="javascript">
           var Identity = '<%=Identity %>' + new Date().toLocaleString();
           var xmlHttp;

           function LoadPage() {
               //            alert(new Date().toGMTString());
               var img = document.getElementById("<%=imgURL.ClientID %>");
               Identity = '<%=Identity %>' + new Date().toLocaleTimeString();
               img.src = "ValidateKey.aspx?Identity=" + Identity;
           }

           function createXMLRequest() {
               if (window.ActiveXObject) {
                   xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
               } else if (window.XMLRequest) {
                   xmlHttp = new XMLHttpRequest;
               } else {
                   alert("不能创建");
               }
           }
           function Test() {
               createXMLRequest(); //调用创建XMLRequest的方法
               xmlHttp.onreadystatechange = handleStatechange;

               var txtCode = document.getElementById("<%=txtCode.ClientID %>");
               xmlHttp.open("GET", "ValidateKey_Validate.ashx?chkCode=" + txtCode.value + "&Identity=" + Identity, false);
               xmlHttp.send(null);
           }


           function handleStatechange() {

               if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {

                   if (xmlHttp.responseText != "验证码通过") {
                       LoadPage();
                   }

                   alert(xmlHttp.responseText);
               }

           }
               LoadPage();
      </script>

 在按钮的Test函数里通过Ajax异步验证来验证显示图片和输入是否一致,

新建一个ashx文件,在这里异步验证是否一致,这里需要注意的是必须实现IRequiresSessionState接口,否则无法使用session。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
namespace WebProject
{
    /// <summary>
    /// Summary description for ValidateKey_Validate
    /// </summary>
    public class ValidateKey_Validate : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            string returnValue = "错误异常";

            string chkCode = "";

            if (string.IsNullOrEmpty(context.Request.QueryString["chkCode"]) == false)
            {
                chkCode = context.Request.QueryString["chkCode"].ToString();
            }

            if (chkCode == "")
            {
                returnValue = "请输入验证码";
            }
            else
            {
                string identity = "";

                string createCode = "";
                if (string.IsNullOrEmpty(context.Request.QueryString["Identity"]) == false)
                {

                    identity = context.Request.QueryString["Identity"].ToString();
                    if (context.Session[identity] != null)
                    {
                        createCode = context.Session[identity].ToString();
                    }

                }

                if ( createCode != "" && identity != "")
                {
                    DateTime createDate = DateTime.MinValue;

                    string[] idenitityValue = identity.Split('_');

                    if (idenitityValue != null && idenitityValue.Length > 1)
                    {
                        DateTime.TryParse(idenitityValue[1], out createDate);

                        if (DateTime.Now - createDate > TimeSpan.FromSeconds(10))
                        {
                            returnValue = "验证码超期";
                        }
                        else
                        {
                            if (createCode.ToLower() != chkCode.ToLower())
                            {
                                returnValue = "验证码不对";
                            }
                            else
                            {
                                returnValue = "验证码通过";
                            }
                        }
                    }
                }

            }

            context.Response.ContentType = "text/plain";
            context.Response.Write(returnValue);

          
        }

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