ASP.NET網站中的驗證碼源代碼

ASP.NET網站中的驗證碼源代碼(純數字、字母數字組合、經常使用498個漢字)

新建一個aspx頁面,源裏面不寫任何入代碼(假如aspx頁面爲yanzhengma1.aspx)緩存

打開yanzhengma1.aspx.cs頁面寫入以下代碼:dom

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Drawing;ide

public partial class yanzhengma : System.Web.UI.Page
{網站

   // private System.IO.MemoryStream ms = new System.IO.MemoryStream();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            yanzhengma yzm = new yanzhengma();
            Session["code1"] = yzm.CreateImage(5, ValidType.Numeric);this

        }       spa

    }code

 

 

    /// <summary>
    /// 驗證碼的類型
    /// </summary>
    public enum ValidType
    {
        /// <summary>
        /// 只有數字
        /// </summary>
        Numeric,
        /// <summary>
        /// 數字和英文字符
        /// </summary>
        NumericAndEnglishChar,
        /// <summary>
        /// 中文字符
        /// </summary>
        ChineseChar
    }orm

    /// <summary>
    /// 生成一個隨機文字圖片,保存在 Session["code1"]
    /// </summary>
    /// <param name="count">圖片中字的個數</param>
    /// <returns>生成的文字</returns>
    public string CreateImage(int count, ValidType type)
    {
        string ValidCode = GenCode(count, type);
      
        switch (type)
        {
            case ValidType.Numeric:
                CreateCheckCodeImage(ValidCode, 13.5);
                break;
            case ValidType.NumericAndEnglishChar:
                CreateCheckCodeImage(ValidCode, 14);
                break;
            case ValidType.ChineseChar:
                CreateCheckCodeImage(ValidCode, 22.5);
                break;
            default:
                break;
        }
        return ValidCode;
    }server

    /// <summary>
    /// 產生隨機字符串
    /// </summary>
    /// <param name="num">隨機出幾個字符</param>
    /// <returns>隨機出的字符串</returns>
    private string GenCode(int num, ValidType type)
    {
        string str;
        switch (type)
        {
            case ValidType.Numeric:
                str = "0123456789";
                break;
            case ValidType.NumericAndEnglishChar:
                str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
                break;
            case ValidType.ChineseChar:圖片

                //經常使用498個漢字
                str = "的一是在不了有和人這中大爲上個國我以要他時來用們生到做地於出就分對成會可主發年動同工也能下過子說產種面而方後多定行學法所民得經十三之進着等部度 家電力裏如水化高自二理起小物現實加量都兩體制機當使點從業本去把性好應開它合還因由其些然前外天政四日那社義事平形相全表間樣與關各從新線內數正心反你 明看原又麼利比或但質氣第向道命此變條只沒結解問意建月公無系軍很情者最立代想已通並提直題黨程展五果料象員革位入常文總次品式活設及管特件長求老頭基資 邊流路級少圖山統接知較將組見計別她手角期根論運農指幾九區強放決西被幹作必戰先回則任取據處隊南給色光門即保治北造百規熱領七海口東導器壓志世金增爭濟 階油思術極交受聯什認六共權收證改清己美再採轉更單風切打白教速花帶安場身車例真務具萬每目至達走積示議聲報鬥完類八離華名確才科張信馬節話米整空元況今 集溫傳土許步羣廣石記需段研界拉林律叫且究觀越織裝影算低持音衆書布覆容兒須際商非驗連斷深難近礦千周委素技備半辦青省列習響約支般史感勞便團往酸歷市克 何除消構府稱太準精值號率族維劃選標寫存候毛親快效斯院查江型眼王按格養易置派層片始卻專狀育廠京識適屬圓包火住調滿縣局照參紅細引聽該鐵價嚴";
                break;
            default:
                str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
                break;
        }

        char[] chastr = str.ToCharArray();
        string code = "";
        Random rd = new Random();
        int i;
        for (i = 0; i < num; i++)
        {
            code += str.Substring(rd.Next(0, str.Length), 1);
        }
        return code;
    }

    /// <summary>
    /// 生成圖片(增長背景噪音線、前景噪音點)
    /// </summary>
    /// <param name="checkCode">隨機出字符串</param>
    private void CreateCheckCodeImage(string checkCode, double codeWidth)
    {
        if (checkCode.Trim() == "" || checkCode == null)
            return;
        System.Drawing.Bitmap p_w_picpath = new System.Drawing.Bitmap((int)(checkCode.Length * codeWidth), 22);
        //string path = Server.MapPath("~/p_w_picpaths/1.jpg");
        //System.Drawing.Image p_w_picpath = System.Drawing.Image.FromFile(path);
        //System.Drawing.Bitmap p_w_picpath = new System.Drawing.Bitmap(path);
        Graphics g = Graphics.FromImage(p_w_picpath);

        try
        {
            //生成隨機生成器
            Random random = new Random();

            //清空圖片背景色
            g.Clear(Color.White);

            // 畫圖片的背景噪音線
            int i;
            for (i = 0; i < 25; i++)
            {
                int x1 = random.Next(p_w_picpath.Width);
                int x2 = random.Next(p_w_picpath.Width);
                int y1 = random.Next(p_w_picpath.Height);
                int y2 = random.Next(p_w_picpath.Height);
                g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
            }

            Font font = new System.Drawing.Font("Verdana", 12, (System.Drawing.FontStyle.Bold));
            System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, p_w_picpath.Width, p_w_picpath.Height), Color.Blue, Color.DarkRed, 1.2F, true);
            //System.Drawing.SolidBrush brush = new System.Drawing.SolidBrush( Color.Blue);
            g.DrawString(checkCode, font, brush, 2, 2, new System.Drawing.StringFormat());

            //畫圖片的前景噪音點
            g.DrawRectangle(new Pen(Color.Silver), 0, 0, p_w_picpath.Width - 1, p_w_picpath.Height - 1);
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            p_w_picpath.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            HttpContext.Current.Response.ExpiresAbsolute = System.DateTime.Now.AddMilliseconds(0);
            //清除該頁輸出緩存,設置該頁無緩存
            //Response.Buffer = true;
            //Response.ExpiresAbsolute = System.DateTime.Now.AddMilliseconds(0);
            //Response.Expires = 0;
            //Response.CacheControl = "no-cache";
            //Response.AppendHeader("Pragma", "No-Cache");

            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.ContentType = "p_w_picpath/JPEG";
            HttpContext.Current.Response.BinaryWrite(ms.ToArray());
            g.Dispose();
            p_w_picpath.Dispose();
        }
        catch
        {
            g.Dispose();
            p_w_picpath.Dispose();

        }
    }

   }

在要插入驗證碼的地方插入以下代碼:(也能夠用 <img>控件,只要是圖片控件都行)

<asp:ImageButton ID="ImageButton7" runat="server" Height="40px" Width="150px" />
                                                <span>點擊圖片更換圖片</span><br /><asp:Label ID="Label1" runat="server" ForeColor="Red" Text = " &nbsp;"> </asp:Label>

好比這是登陸頁面,當頁面加載的時候就須要用到驗證碼,故在代碼的page_load() 中插入代碼:this.ImageButton7.ImageUrl = "yanzhengma1.aspx"; 這樣當頁面加載 的時候就會出現驗證碼了。

點擊登陸按鈕時的代碼:

protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {

        if (tbyanzhengma.Text.Trim() == Session["code1"].ToString())
        {
             Lable1.Text="輸入的驗證碼正確";
        }
        else
        {
            Label1.Text = "輸入的驗證碼錯誤";
        }
    }

當要更換驗證碼的時候點擊p_w_picpathbutton時的代碼:

protected void ImageButton7_Click(object sender, ImageClickEventArgs e)
    {
        this.ImageButton7.ImageUrl = "yanzhengma1.aspx";
    }

 

驗證碼到此就大功告成了!!這些代碼是用VS2008寫成!經本人實踐可用!

相關文章
相關標籤/搜索