asp.net+jquery 验证码

一个基于asp.net的简单验证码验证:

1.普通的字符串验证

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="YanZhengMa.Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>jQuery</title>
    <script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
    <script type="text/javascript">
        $(function () {
            //刷新CheckCode
            $("#img1").click(function () {
                newCheckCode();
            });
            $("#a1").click(function () {
                newCheckCode();
            });
            //提交验证码
            $("#btn").click(function () {
                //                $.get("ajax.aspx",
                //                { code: $("#txt").val() }, 
                //                function (result) {
                //                    result = trim(result);
                //                    if (result == "t") {
                //                        alert("验证码正确!");
                //                    }
                //                    else {
                //                        alert("验证码错误!");
                //                        newCheckCode();
                //                    }
                //                });
                $.ajax({
                    type: "Post",
                    url: "Default.aspx/VerificationCode",
                    data: "{'code':'" + $("#txt").val()+"'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        switch (data.d) {
                            case 1:
                                alert("验证码正确!");
                                break;
                            default:
                                alert("验证码错误!");
                                newCheckCode();
                                break;
                        }
                    },
                    error: function (err) {
                        alert('出错了' + err);
                    }
                });
            });
        });

        function trim(str) { //删除左右两端的空格 
            return str.replace(/(^\s*)|(\s*$)/g, "");
        }

        function newCheckCode() {//刷新验证码
            $("#img1").attr("src", "CheckCode.aspx");
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table>
            <tr valign="bottom">
                <td>
                    <input type="text" id="txt" maxlength="5" />
                </td>
                <td>
                    <img id="img1" src="CheckCode.aspx" alt="看不清,换一个" />
                </td>
                <td>
                    <a id="a1" style="cursor: pointer; font-size: 12px;">看不清,换一个</a>
                </td>
                <td>
                    <input type="button" id="btn" value="提交" />
                </td>
            </tr>
        </table>
    </div>

    <br />
    <br />
    <div>
        <span>验证码:</span> <span>
        <img alt="看不清楚?请点击刷新" οnclick="this.src=this.src+'?'+Math.random();" 
            src="Code.aspx" style="CURSOR:hand;" /></span>
        <asp:TextBox ID="txtCode" runat="server"></asp:TextBox>
        <asp:Button ID="btnOK" runat="server" οnclick="btnOK_Click" Text="验证" />
    </div>
    <br />
    <br />
    </form>
</body>
</html>

 生成字符串验证码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;

namespace YanZhengMa
{
    public partial class CheckCode : System.Web.UI.Page
    {
        public static string checkKeyCode=string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            this.CreateCheckCodeImage(GenerateCheckCode());
        }

        private string GenerateCheckCode()
        {
            int number;
            char code;
            string checkCode = String.Empty;

            System.Random random = new Random();

            for (int i = 0; i < 5; i++)
            {
                number = random.Next();

                if (number % 2 == 0)
                    code = (char)('0' + (char)(number % 10));//随机数字
                else
                    code = (char)('A' + (char)(number % 26));//随机字母

                checkCode += code.ToString();
            }
            Session和Cookie两种方法根据习惯,选一种使用即可。

            #region 用Session
            //Session["CheckCode"] = checkCode.ToLower();//请读取此Session:Session["CheckCode"].ToString();//字母统一为小写
            //Session.Timeout = 10;//10分钟
            #endregion

            #region 用Cookie
            HttpCookie cookies = new HttpCookie("CheckCode");
            cookies.Values.Add("checkCode", checkCode.Trim().ToLower());//请读取此cookie:"CheckCode",判断验证码,字母为小写
            cookies.Expires = DateTime.Now.AddMinutes(10);//10分钟
            Response.AppendCookie(cookies);//生成Cookie
            #endregion

            #region 用静态变量

            checkKeyCode = checkCode;

            #endregion

            return checkCode;//返回并生成图片
        }

        private void CreateCheckCodeImage(string checkCode)
        {
            if (checkCode == null || checkCode.Trim() == String.Empty)
                return;

            System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 14.5)), 22);
            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.GreenYellow), x1, y1, x2, y2);
                }

                Font font = new System.Drawing.Font("Verdana", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
                System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
                g.DrawString(checkCode, font, brush, 2, 2);

                //画图片的前景噪音点
                for (int i = 0; i < 80; 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.Red), 0, 0, image.Width - 1, image.Height - 1);

                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                Response.ClearContent();
                Response.ContentType = "image/Gif";
                Response.BinaryWrite(ms.ToArray());
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }
    }
}

 ajax后台执行类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace YanZhengMa
{
    public partial class ajax : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Request.QueryString["code"]))
            {
                string myCode = Request.QueryString["code"].ToString().Trim().ToLower();//统一为小写
                #region 用Session
                //if (Session["CheckCode"] != null && Session["CheckCode"].ToString().Trim() != "")
                //{
                //    if (myCode == Session["CheckCode"].ToString())
                //    {
                //        Response.Write("t");//正确
                //    }
                //    else
                //    {
                //        Response.Write("f");//错误
                //    }
                //}
                //else
                //{
                //    Response.Write("null");//空值,提示重刷验证码
                //}
                #endregion

                #region 用Cookie

                HttpCookie cookies = Request.Cookies["CheckCode"];

                if (cookies != null)
                {
                    if (myCode == cookies.Values["checkCode"].ToString().Trim().ToLower())
                    {
                        Response.Write("1");//正确
                    }
                    else
                    {
                        Response.Write("0");//错误
                    }
                }
                else
                {
                    Response.Write("0");//错误
                }
                #endregion
            }
            else
            {
                Response.Write("0");//错误
            }
        }
    }
}

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;

namespace YanZhengMa
{
    public partial class Default : System.Web.UI.Page
    {

        [WebMethod]
        public static int VerificationCode(string code)
        {
            if (string.IsNullOrWhiteSpace(code))
                return 2;
            string checkKeyCode = CheckCode.checkKeyCode;
            if (!string.IsNullOrWhiteSpace(checkKeyCode))
            {
                if (code.Trim().ToLower() == checkKeyCode.Trim().ToLower())
                {
                    return 1;//正确
                }
                else
                {
                    return 2;//错误
                }
            }
            else
            {
                return 2;//错误
            }
        }

        private string str = "";
        protected void btnOK_Click(object sender, EventArgs e)
        {
            //str = Session["key"].ToString();
            str = Code.ss;

            if (txtCode.Text == str)
            {
               Response.Write("<script>alert('验证通过!!!');</script>");
                //Response.Write("<script>alert('验证通过!!!');window.location.href='Default.aspx';</script>");
            }
            else
                Response.Write("<script>alert('验证码输入有误,请重新输入!!!')</script>");
        }
    }
}

 

 2.算法验证码图片生成类

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

namespace YanZhengMa
{
    /// <summary> 
    /// 数学算式的验证码 
    /// </summary> 
    public static class SecurityCode
    {
        #region 生成图片
        //static string SecurityCodes, Securityimgresult;

        public static string Output()
        {
            int mathResult = 0;
            string expression = null;
            Random rnd = new Random();
            生成3个10以内的整数,用来运算 
            int operator1 = rnd.Next(0, 10);
            int operator2 = rnd.Next(0, 10);
            int operator3 = rnd.Next(0, 10);
            随机组合运算顺序,只做 + 和 * 运算 
            switch (rnd.Next(0, 3))
            {
                case 0:
                    mathResult = operator1 + operator2 * operator3;
                    expression = string.Format("{0} + {1} x {2} = ?", operator1, operator2, operator3);
                    break;
                case 1:
                    mathResult = operator1 * operator2 + operator3;
                    expression = string.Format("{0} x {1} + {2} = ?", operator1, operator2, operator3);
                    break;
                default:
                    mathResult = operator2 + operator1 * operator3;
                    expression = string.Format("{0} + {1} x {2} = ?", operator2, operator1, operator3);
                    break;
            }

            return expression + ";" + mathResult.ToString().Trim();
        }
        /// <summary> 
        /// 输出验证码表达式到浏览器 
        /// </summary> 
        /// <param name="context">httpcontext</param> 
        /// <param name="sessionKey"></param> 
        public static void OutputImage(string expression, System.Web.HttpContext context)
        {
            Random rnd = new Random();
            //string[] str = Output().Split(';');
            //string expression = str[0];
            //string result=str[1];
            using (Bitmap bmp = new Bitmap(80, 25))
            {
                using (Graphics graph = Graphics.FromImage(bmp))
                {
                    graph.Clear(Color.FromArgb(232, 238, 247)); 背景色,可自行设置 


                    for (int i = 0; i <= 128; i++)
                    {
                        graph.DrawRectangle(
                        new Pen(Color.FromArgb(rnd.Next(0, 255), rnd.Next(0, 255), rnd.Next(0, 255))),
                        (float)rnd.Next(2, 128),
                        (float)rnd.Next(2, 38),
                        0.1F, //噪点的粒度 
                        0.1F);//噪点的粒度,可以调节这两个值,到认为自己满意 
                    }

                    输出表达式 
                    for (int i = 0; i < expression.Length; i++)
                    {
                        graph.DrawString(expression.Substring(i, 1),
                        new Font(FontFamily.GenericSansSerif, 12, FontStyle.Bold),
                        new SolidBrush(Color.FromArgb(rnd.Next(255), rnd.Next(128), rnd.Next(255))),
                        1 + i * 5,
                        rnd.Next(1, 5));
                    }
                    画边框,不需要可以注释掉 
                    graph.DrawRectangle(new Pen(Color.Firebrick), 0, 0, 80 - 1, 25 - 1);
                }

                禁用缓存 
                DisableHttpCache(context);
                输出图片到浏览器,我采用的是 gif 格式,可自行设置其他格式 
                context.Response.ContentType = "image/gif";
                bmp.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
                context.Response.End();

            }

        }
        #endregion
        /// <summary> 
        /// 禁用缓存 
        /// </summary> 
        /// <param name="context">httpcontext</param> 
        private static void DisableHttpCache(System.Web.HttpContext context)
        {
            清除http缓存 
            context.Response.ClearHeaders();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace YanZhengMa
{
    public partial class Code : System.Web.UI.Page
    {
        public string str = SecurityCode.Output();
        public static string ss = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string[] strs = str.Split(';');
                string expression = strs[0];
                ss = str.Split(';')[1];

                SecurityCode.OutputImage(expression, HttpContext.Current);

                //string str=  sc.OutputImage(HttpContext.Current); //key是保存验证码结果的SESSION的key 
                //Session["key"] = str;

            }
        }
    }
}
  context.Response.ClearContent(); 禁用http缓存  http 1.1 context.Response.AddHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT"); context.Response.AddHeader("Cache-Control", "no-store, no-cache, max-age=0, must-revalidate");  http 1.0 context.Response.AddHeader("Pragma", "no-cache"); } } }

 后台处理生成的验证码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值