• C#验证码使用


    1、C#创建验证码

    1.1 创建获取验证码页面(ValidateCode.aspx)

    1. <html xmlns="http://www.w3.org/1999/xhtml">  
    2. <head runat="server">  
    3.     <title>获取验证码</title>  
    4. </head>  
    5. <body>  
    6.     <form id="form1" runat="server">  
    7.         <div>获取验证码</div>  
    8.     </form>  
    9. </body>  
    10. </html>  
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>获取验证码</title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>获取验证码</div>
        </form>
    </body>
    </html>


    1.2 编写获取验证码代码(ValidateCode.aspx.cs)

    1. /// <summary>   
    2. /// 验证码类型(0-字母数字混合,1-数字,2-字母)   
    3. /// </summary>   
    4. private string validateCodeType = "0";  
    5. /// <summary>   
    6. /// 验证码字符个数   
    7. /// </summary>   
    8. private int validateCodeCount = 4;  
    9. /// <summary>   
    10. /// 验证码的字符集,去掉了一些容易混淆的字符   
    11. /// </summary>   
    12. 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' };  
    13.   
    14. protected void Page_Load(object sender, EventArgs e)  
    15. {  
    16.     //取消缓存   
    17.     Response.BufferOutput = true;  
    18.     Response.Cache.SetExpires(DateTime.Now.AddMilliseconds(-1));  
    19.     Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);  
    20.     Response.AppendHeader("Pragma""No-Cache");  
    21.     //获取设置参数   
    22.     if (!string.IsNullOrEmpty(Request.QueryString["validateCodeType"]))  
    23.     {  
    24.         validateCodeType = Request.QueryString["validateCodeType"];  
    25.     }  
    26.     if (!string.IsNullOrEmpty(Request.QueryString["validateCodeCount"]))  
    27.     {  
    28.         int.TryParse(Request.QueryString["validateCodeCount"], out validateCodeCount);  
    29.     }  
    30.     //生成验证码   
    31.     this.CreateCheckCodeImage(GenerateCheckCode());  
    32. }  
    33.   
    34. private string GenerateCheckCode()  
    35. {  
    36.     char code ;  
    37.     string checkCode = String.Empty;  
    38.     System.Random random = new Random();  
    39.   
    40.     for (int i = 0; i < validateCodeCount; i++)  
    41.     {  
    42.         code = character[random.Next(character.Length)];  
    43.   
    44.         // 要求全为数字或字母   
    45.         if (validateCodeType == "1")  
    46.         {  
    47.             if ((int)code < 48 || (int)code > 57)  
    48.             {  
    49.                 i--;  
    50.                 continue;  
    51.             }  
    52.         }  
    53.         else if (validateCodeType == "2")  
    54.         {  
    55.             if ((int)code < 65 || (int)code > 90)  
    56.             {  
    57.                 i--;  
    58.                 continue;  
    59.             }  
    60.         }  
    61.         checkCode += code;  
    62.     }  
    63.   
    64.     Response.Cookies.Add(new System.Web.HttpCookie("CheckCode", checkCode));  
    65.     this.Session["CheckCode"] = checkCode;  
    66.     return checkCode;  
    67. }  
    68.   
    69. private void CreateCheckCodeImage(string checkCode)  
    70. {  
    71.     if (checkCode == null || checkCode.Trim() == String.Empty)  
    72.         return;  
    73.   
    74.     System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length*15.0+40)), 23);  
    75.     System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);  
    76.   
    77.     try  
    78.     {  
    79.         //生成随机生成器   
    80.         Random random = new Random();  
    81.   
    82.         //清空图片背景色   
    83.         g.Clear(System.Drawing.Color.White);  
    84.   
    85.         //画图片的背景噪音线   
    86.         for (int i = 0; i < 25; i++)  
    87.         {  
    88.             int x1 = random.Next(image.Width);  
    89.             int x2 = random.Next(image.Width);  
    90.             int y1 = random.Next(image.Height);  
    91.             int y2 = random.Next(image.Height);  
    92.   
    93.             g.DrawLine(new System.Drawing.Pen(System.Drawing.Color.Silver), x1, y1, x2, y2);  
    94.         }  
    95.   
    96.         System.Drawing.Font font = new System.Drawing.Font("Arial", 14, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));  
    97.         System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new System.Drawing.Rectangle(0, 0, image.Width, image.Height), System.Drawing.Color.Blue, System.Drawing.Color.DarkRed, 1.2f, true);  
    98.   
    99.         int cySpace = 16;  
    100.         for (int i = 0; i < validateCodeCount; i++)  
    101.         {  
    102.             g.DrawString(checkCode.Substring(i, 1), font, brush, (i + 1) * cySpace, 1);  
    103.         }  
    104.   
    105.         //画图片的前景噪音点   
    106.         for (int i = 0; i < 100; i++)  
    107.         {  
    108.             int x = random.Next(image.Width);  
    109.             int y = random.Next(image.Height);  
    110.   
    111.             image.SetPixel(x, y, System.Drawing.Color.FromArgb(random.Next()));  
    112.         }  
    113.   
    114.         //画图片的边框线   
    115.         g.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Silver), 0, 0, image.Width - 1, image.Height - 1);  
    116.   
    117.         System.IO.MemoryStream ms = new System.IO.MemoryStream();  
    118.         image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);  
    119.         Response.ClearContent();  
    120.         Response.ContentType = "image/Gif";  
    121.         Response.BinaryWrite(ms.ToArray());  
    122.     }  
    123.     finally  
    124.     {  
    125.         g.Dispose();  
    126.         image.Dispose();  
    127.     }  
    128. }  
    /// <summary>
    /// 验证码类型(0-字母数字混合,1-数字,2-字母)
    /// </summary>
    private string validateCodeType = "0";
    /// <summary>
    /// 验证码字符个数
    /// </summary>
    private int validateCodeCount = 4;
    /// <summary>
    /// 验证码的字符集,去掉了一些容易混淆的字符
    /// </summary>
    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' };
    
    protected void Page_Load(object sender, EventArgs e)
    {
        //取消缓存
        Response.BufferOutput = true;
        Response.Cache.SetExpires(DateTime.Now.AddMilliseconds(-1));
        Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
        Response.AppendHeader("Pragma", "No-Cache");
        //获取设置参数
        if (!string.IsNullOrEmpty(Request.QueryString["validateCodeType"]))
        {
            validateCodeType = Request.QueryString["validateCodeType"];
        }
        if (!string.IsNullOrEmpty(Request.QueryString["validateCodeCount"]))
        {
            int.TryParse(Request.QueryString["validateCodeCount"], out validateCodeCount);
        }
        //生成验证码
        this.CreateCheckCodeImage(GenerateCheckCode());
    }
    
    private string GenerateCheckCode()
    {
        char code ;
        string checkCode = String.Empty;
        System.Random random = new Random();
    
        for (int i = 0; i < validateCodeCount; i++)
        {
            code = character[random.Next(character.Length)];
    
            // 要求全为数字或字母
            if (validateCodeType == "1")
            {
                if ((int)code < 48 || (int)code > 57)
                {
                    i--;
                    continue;
                }
            }
            else if (validateCodeType == "2")
            {
                if ((int)code < 65 || (int)code > 90)
                {
                    i--;
                    continue;
                }
            }
            checkCode += code;
        }
    
        Response.Cookies.Add(new System.Web.HttpCookie("CheckCode", checkCode));
        this.Session["CheckCode"] = checkCode;
        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*15.0+40)), 23);
        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);
    
        try
        {
            //生成随机生成器
            Random random = new Random();
    
            //清空图片背景色
            g.Clear(System.Drawing.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 System.Drawing.Pen(System.Drawing.Color.Silver), x1, y1, x2, y2);
            }
    
            System.Drawing.Font font = new System.Drawing.Font("Arial", 14, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
            System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new System.Drawing.Rectangle(0, 0, image.Width, image.Height), System.Drawing.Color.Blue, System.Drawing.Color.DarkRed, 1.2f, true);
    
            int cySpace = 16;
            for (int i = 0; i < validateCodeCount; i++)
            {
                g.DrawString(checkCode.Substring(i, 1), font, brush, (i + 1) * cySpace, 1);
            }
    
            //画图片的前景噪音点
            for (int i = 0; i < 100; i++)
            {
                int x = random.Next(image.Width);
                int y = random.Next(image.Height);
    
                image.SetPixel(x, y, System.Drawing.Color.FromArgb(random.Next()));
            }
    
            //画图片的边框线
            g.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Silver), 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();
        }
    }

    2、验证码的使用

    2.1 验证码的前段显示代码

    1. <img src="/ValidateCode.aspx?ValidateCodeType=1&0.011150883024061309" onclick="this.src='/ValidateCode.aspx?ValidateCodeType=1&'+Math.random();" id="imgValidateCode" alt="点击刷新验证码" title="点击刷新验证码" style="cursor: pointer;">  
    <img src="/ValidateCode.aspx?ValidateCodeType=1&0.011150883024061309" onclick="this.src='/ValidateCode.aspx?ValidateCodeType=1&'+Math.random();" id="imgValidateCode" alt="点击刷新验证码" title="点击刷新验证码" style="cursor: pointer;">
    

    2.2 创建验证码测试页面(ValidateTest.aspx)

    1. <html xmlns="http://www.w3.org/1999/xhtml">  
    2. <head runat="server">  
    3.     <title>验证码测试</title>  
    4. </head>  
    5. <body>  
    6.     <form id="form1" runat="server">  
    7.     <div>  
    8.         <input runat="server" id="txtValidate" />  
    9.         <img src="/ValidateCode.aspx?ValidateCodeType=1&0.011150883024061309" onclick="this.src='/ValidateCode.aspx?ValidateCodeType=1&'+Math.random();" id="imgValidateCode" alt="点击刷新验证码" title="点击刷新验证码" style="cursor: pointer;">  
    10.         <asp:Button runat="server" id="btnVal" Text="提交" onclick="btnVal_Click"  />  
    11.     </div>  
    12.     </form>  
    13. </body>  
    14. </html>  
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>验证码测试</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <input runat="server" id="txtValidate" />
            <img src="/ValidateCode.aspx?ValidateCodeType=1&0.011150883024061309" onclick="this.src='/ValidateCode.aspx?ValidateCodeType=1&'+Math.random();" id="imgValidateCode" alt="点击刷新验证码" title="点击刷新验证码" style="cursor: pointer;">
            <asp:Button runat="server" id="btnVal" Text="提交" onclick="btnVal_Click"  />
        </div>
        </form>
    </body>
    </html>

    2.3 编写验证码测试的提交代码(ValidateTest.aspx.cs)

    1. protected void btnVal_Click(object sender, EventArgs e)  
    2. {  
    3.     bool result = false;   //验证结果   
    4.     string userCode = this.txtValidate.Value; //获取用户输入的验证码   
    5.     if (String.IsNullOrEmpty(userCode))  
    6.     {   
    7.         //请输入验证码   
    8.         return;  
    9.     }  
    10.   
    11.     string validCode = this.Session["CheckCode"as String;  //获取系统生成的验证码   
    12.     if (!string.IsNullOrEmpty(validCode))  
    13.     {  
    14.         if (userCode.ToLower() == validCode.ToLower())  
    15.         {  
    16.             //验证成功   
    17.             result = true;  
    18.         }  
    19.         else  
    20.         {  
    21.             //验证失败   
    22.             result = false;  
    23.         }  
    24.     }  
    25. }  
  • 相关阅读:
    Page6:关于能控性、能观性、能测性及其判据(1)[Linear System Theory]
    Page5:状态转移矩阵及性质、连续线性系统离散化及其性质[Linear System Theory]
    java线程学习之notify方法和notifyAll方法
    java线程学习之wait方法
    java线程学习之synchronized关键字
    java线程学习之Sleep方法
    java线程学习之线程创建
    用javaScript获取页面元素值
    用javaScript对页面元素进行显示和隐藏
    JDBC工具类
  • 原文地址:https://www.cnblogs.com/wwwfj/p/3207441.html
Copyright © 2020-2023  润新知