1. 程式人生 > >.net 實現三種驗證碼(漢字驗證碼,數字驗證碼,數字+英文驗證)附帶登陸驗證例項

.net 實現三種驗證碼(漢字驗證碼,數字驗證碼,數字+英文驗證)附帶登陸驗證例項

首先,新建createImage.aspx

在CreateImage.aspx.cs中,新增如下程式碼:

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

public partial class CreateImage : System.Web.UI.Page
{
        protected void Page_Load(object sender, EventArgs e)
        {
           // string checkCode=CreateNumCode(4);//生成四位數字驗證碼
            string checkCode = CreateCode(4);//生成四位數字+字母驗證
            //string checkCode = GetString(4);//生成四位漢字驗證碼
            Session["CheckCode"] = checkCode;
            CreateImages(checkCode);
        }
        /*產生數字+字母驗證碼*/
    /*演算法思想:將所有數字及字母儲存在字串中,呼叫Random()函式隨機選取子字串陣列中的一個字元,加入
     指定的字串末尾,如此反覆,最終返回生成好的驗證碼*/
        public string CreateCode(int codeLength)
        {
            string so = "1,2,3,4,5,6,7,8,9,0,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
            string[] strArr=so.Split(',');
            string code = "";
            Random rand=new Random();
            for (int i = 0; i < codeLength; i++)
            {
                code+=strArr[rand.Next(0, strArr.Length)];
            }
            Session["CheckCode"] = code;

            return code;
        }

        private string CreateNumCode(int codeCount) //生成純數字驗證碼
        {
            string allChar = "0,1,2,3,4,5,6,7,8,9";
            string[] allCharArray = allChar.Split(',');//將allChar的每個由逗號分隔的元素新增到陣列中
            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(9);//返回一個小於9的非負隨機數
                if (temp == t) //保證連續兩個生成的隨機數不同
                {
                    return CreateNumCode(codeCount);
                }
                temp = t;
                randomCode += allCharArray[t];
            }
            Session["CheckCode"] = randomCode;
            return randomCode;

        }

        /**/
        /* 
    此函式在漢字編碼範圍內隨機建立含兩個元素的十六進位制位元組陣列,每個位元組陣列代表一個漢字,並將 
    四個位元組陣列儲存在object陣列中。 
    引數:strlength,代表需要產生的漢字個數 
    */
        public static object[] CreateChiCode(int strlength)
        {
            //定義一個字串陣列儲存漢字編碼的組成元素 
            string[] rBase = new String[16] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
            Random rnd = new Random();
            //定義一個object陣列用來存放隨機生成的漢字
            object[] bytes = new object[strlength];

            /**/
            /*每迴圈一次產生一個含兩個元素的十六進位制位元組陣列,並將其放入bject陣列中 
         每個漢字有四個區位碼組成 
         區位碼第1位和區位碼第2位作為位元組陣列第一個元素 
         區位碼第3位和區位碼第4位作為位元組陣列第二個元素 
        */
            for (int i = 0; i < strlength; i++)
            {
                //區位碼第1位 
                int r1 = rnd.Next(11, 14);//返回一個介於11到14的隨機數
                string str_r1 = rBase[r1].Trim();

                //區位碼第2位 
                rnd = new Random(r1 * unchecked((int)DateTime.Now.Ticks) + i);//更換隨機數發生器的種子避免產生重複值 
                int r2;
                if (r1 == 13)
                {
                    r2 = rnd.Next(0, 7);
                }
                else
                {
                    r2 = rnd.Next(0, 16);
                }
                string str_r2 = rBase[r2].Trim();

                //區位碼第3位 
                rnd = new Random(r2 * unchecked((int)DateTime.Now.Ticks) + i);
                int r3 = rnd.Next(10, 16);
                string str_r3 = rBase[r3].Trim();

                //區位碼第4位 
                rnd = new Random(r3 * unchecked((int)DateTime.Now.Ticks) + i);
                int r4;
                if (r3 == 10)
                {
                    r4 = rnd.Next(1, 16);
                }
                else if (r3 == 15)
                {
                    r4 = rnd.Next(0, 15);
                }
                else
                {
                    r4 = rnd.Next(0, 16);
                }
                string str_r4 = rBase[r4].Trim();

                //定義兩個位元組變數儲存產生的隨機漢字區位碼 
                byte byte1 = Convert.ToByte(str_r1 + str_r2, 16);
                byte byte2 = Convert.ToByte(str_r3 + str_r4, 16);
                //將兩個位元組變數儲存在位元組陣列中 
                byte[] str_r = new byte[] { byte1, byte2 };

                //將產生的一個漢字的位元組陣列放入object陣列中 
                bytes.SetValue(str_r, i);
            }
            return bytes;
        }
        private string GetString(int length)  //生成指定位數的漢字驗證碼,並轉換為String型別
        {
            object[] obj=CreateChiCode(length);
            Encoding gb = Encoding.GetEncoding("gb2312");
            String[] bytes= new String[length];
            String code = "";
            for (int i = 0; i < length; i++)
            {
                bytes[i] = gb.GetString((byte[])Convert.ChangeType(obj[i], typeof(byte[])));
               // bytes[i] = obj[i].ToString();
                code = code+bytes[i];
            }
            Session["CheckCode"] = code;
            return code;
        }

        /*產生驗證圖片*/
    public void CreateImages(string code)
    {
        Bitmap image = new Bitmap(120, 40);
        Graphics g = Graphics.FromImage(image);
        WebColorConverter ww=new WebColorConverter();
        g.Clear((Color)ww.ConvertFromString("#FAE264"));
        Random random = new Random();
        //畫圖片的背景噪音線
        for (int i = 0; i < 12; 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.LightGray), x1, y1, x2, y2);
        }
        Font font = new Font("Arial", 15, FontStyle.Bold | FontStyle.Italic);
        System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0,0,image.Width,image.Height),Color.Blue,Color.Gray,1.2f,true);
        g.DrawString(code, font, brush, 0, 0);
        //畫圖片的前景噪音點
        for (int i = 0; i < 10; i++)
        {
            int x = random.Next(image.Width);
            int y = random.Next(image.Height);
            image.SetPixel(x, y, Color.White);
        }
        //畫圖片的邊框線
        g.DrawRectangle(new Pen(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());
        g.Dispose();image.Dispose();
    }
    #region Web 窗體設計器生成的程式碼
    override protected void OnInit(EventArgs e)
    {
        //
        // CODEGEN: 該呼叫是 ASP.NET Web 窗體設計器所必需的。
        //
        InitializeComponent();
        base.OnInit(e);
    }
        /// <summary>
        /// 設計器支援所需的方法 - 不要使用程式碼編輯器修改
        /// 此方法的內容。
        /// </summary>
        private void InitializeComponent()
        {
            this.Load += new System.EventHandler(this.Page_Load);
        }
    #endregion
}


CreateImage.aspx中不需新增任何程式碼

之後,新建webform1.aspx

在網頁中新增如下程式碼:

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
 <html>
 <head>
 <title>WebForm1
 </title>
 <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1"/>
 <meta name="CODE_LANGUAGE" Content="C#"/>
 <meta name="vs_defaultClientScript" content="JavaScript"/>
 <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"/>
 </head>
 <body MS_POSITIONING="gridlayout">
 <form id="Form1" method="post" runat="server">
 <img src="CreateImage.aspx" align="middle" >
 <BR>
 </form>
 </body>
 </html>


對應的cs檔案中不需新增任何程式碼,此時即可完成

看看效果吧

附加一個登陸介面應用驗證碼的例項:

新建login.aspx

login.aspx中

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="login.aspx.cs" Inherits="login" %>

<!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></title>
</head>
<body>
    <form id="form1" runat="server">
         <div id="login">
         <table cellpadding="0" cellspacing="0" border="0" style="width: 400px">
             <tr>
                 <td>
                     <span>賬號</span>
                 </td>
                 <td>
                      <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                 </td>
             </tr>
             <tr>
                 <td>
                     <span>密碼</span>
                 </td>
                 <td>
                      <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                 </td>
             </tr>
             <tr>
                 <td>
                     <span>驗證碼</span>
                 </td>
                 <td>
                      
                     <asp:TextBox ID="TextBox3" runat="server" Width="120px"></asp:TextBox>
                     <img src="CreateImage.aspx" alt="點選重新整理" id="imgValidateCode" style="width:100px; height:40px;line-height:30px;vertical-align:middle;" />                   
                 </td>
             </tr>
             <tr>
                 <td colspan="2">
                     <div style="margin-left: 42px">
                          
                         <asp:Button ID="Button1" runat="server" onclick="Button1_Click1" Text="登陸" />
  
                         <asp:Button ID="Button2" runat="server" onclick="Button2_Click1" Text="重置" />
                     </div>
                 </td>
             </tr>
         </table>
     </div>
    </form>
</body>
</html>


對應的cs檔案中,

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

public partial class login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        
    } 
    protected void Button1_Click1(object sender, EventArgs e)
    {
        string checkCode = this.TextBox3.Text.Trim();
        //判斷驗證碼是否為空
        if (checkCode == "" || checkCode == null)
        {
            this.Page.ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), "<script>alert('請輸入驗證碼!');</script>");
            return;
        }
        else
        {
            //判斷驗證碼輸入是否正確
            if (String.Compare(Session["CheckCode"].ToString(), checkCode, true) != 0) //compare函式可以選擇是否忽略大小寫
            {
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), "<script>alert('驗證碼錯誤!');</script>");
                return;
            }
            else if (String.Compare(Session["CheckCode"].ToString(), checkCode, true) == 0)
            {
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), "<script>alert('驗證成功!');</script>");
                return;
            }
        }
    }
    protected void Button2_Click1(object sender, EventArgs e)
    {
        this.TextBox1.Text = "";
        this.TextBox3.Text = "";
        this.TextBox2.Text = "";
    }
}

看看效果