ASp.Net自訂驗證碼控制項

來源:互聯網
上載者:User

    最近自己寫了一個自訂驗證碼控制項把它拿出來和大家分享分享

 具體步驟

1---》建立asp.net 網站

2---》添加建立項目 ,選擇類庫

3---》建立兩個類

     3.1--》自訂控制項類(WebControl 衍生類別)

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

namespace AuthCode
{
    [ToolboxData("〈{0}:AuthCode runat=server>〈/{0}:AuthCode>")]
    public class AuthCode : WebControl
    {
        /// 〈summary>
        /// 獲得驗證碼的值
        /// 〈/summary>
        /// 〈returns>驗證碼〈/returns>
        public string GetValue()
        {
            return HttpContext.Current.Session["value"].ToString();
        }
        [Bindable(true)]
        [Category("Appearance")]
        [Description("驗證碼字元長度")]
        [DefaultValue("ss")]
        [Localizable(true)]
        //長度
        internal static int mySize;

        public int MySize
        {
            get { return AuthCode.mySize; }
            set
            {
                AuthCode.mySize = value;
              
            }
        }
      

        public AuthCode()
            : base(HtmlTextWriterTag.Img)//重寫父類的構造(輸出資料流的HTML標記)
        { }
        protected override void AddAttributesToRender(HtmlTextWriter writer)
        {
            base.AddAttributesToRender(writer);//將要輸出的的HTML標籤的屬性和樣式添加到指定的 HtmlTextWriter中
            writer.AddStyleAttribute(HtmlTextWriterStyle.Cursor, "pointer");//添加樣式

            /**-
             * 圖片的onclick事件 "this.src='VerifyImg.jd?id='+Math.random()"
             * 每次單擊一次就有一個新的圖片請求路徑(VerifyImg.jd?id='+Math.random())參數只是
             * 告訴瀏覽器這是一個新的請求然後經過 IHttpHander處理產生新的圖片 id 沒有任何實際意思(創造一個新的請求)
             * -**/
            writer.AddAttribute("onclick", "this.src='img.jd?id='+Math.random()");//添加js VerifyImg.jd

            writer.AddAttribute(HtmlTextWriterAttribute.Src, "img.jd");
            writer.AddAttribute("alt", "點擊重新整理");
        }

    }
}
 

      3.2--》建立處理類(必須實現 IHttpHandler,IRequiresSessionState 兩個介面)

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

namespace AuthCode
{
   public class AuthCodeHttpHander:IHttpHandler,IRequiresSessionState
    {
        /// 〈summary>
        /// 返回驗證碼字元
        /// 〈/summary>
        /// 〈param name="codeCount">驗證碼長度〈/param>
        /// 〈returns>〈/returns>
        private string GetRandomNumberString(int codeCount)
        {
            string strChoice = "2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,U,V,W,X,Y,Z";
            string[] strResult = strChoice.Split(new Char[] { ',' });
            string strReturn = "";
            Random rnd = new Random();
            for (int i = 0; i 〈 codeCount; i++)
            {
                int j = rnd.Next(strResult.Length);//隨機數不能大於數組的長度
                strReturn = strReturn + strResult[j].ToString();
            }
            return strReturn;
        }

        private Color GetColor()
        {
            return Color.Black;
        }
        private Bitmap CreateImage(string str_AuthCode)
        {
            /* -----------------------------繪製圖片的樣式 ------------------------------------*/

            int width =str_AuthCode.Length* 21;
            int height = 30;
            Random rad = new Random();
            Bitmap bmp = new Bitmap(width, height);
            Graphics grp = Graphics.FromImage(bmp);// 在圖片上繪製圖形
            grp.Clear(Color.YellowGreen);//填充bmp的背景色
            grp.DrawRectangle(new Pen(Color.Red, 1), 0, 0, width - 1, height - 1);//繪製邊框
            int num = width * height;
            for (int i = 0; i 〈 num; i++)//在圖片的指定座標上畫上有顏色的圓點
            {
                int x = rad.Next(width);
                int y = rad.Next(height);
                int r = rad.Next(255);
                int g = rad.Next(255);
                int b = rad.Next(255);
                Color c = Color.FromArgb(r, g, b);
                bmp.SetPixel(x, y, c);//在圖片的指定座標上畫上有顏色的圓點
            }

            /*-------------------------- 在圖片繪製字串------------------------------------ */

            Font f = new Font("宋體", 20, FontStyle.Bold);//定義字型
            Brush br = new SolidBrush(Color.Black);//定義畫筆的顏色 及字型的顏色
            for (int i = 0; i 〈 str_AuthCode.Length; i++)
            {
                string s = str_AuthCode.Substring(i, 1);//單個單個的將字畫到圖片上
                Point p = new Point(i * 20 + rad.Next(3), rad.Next(3) + 1);//字型出現的位置(座標)
                grp.DrawString(s, f, br, p);//繪製字串
            }
            grp.Dispose();
            return bmp;//返回

        }

        /// 〈summary>
        /// 是否可以處理遠端HTTP請求
        /// 〈/summary>
        public bool IsReusable
        {
            get { return true; }
        }

        /// 〈summary>
        /// 將驗證碼圖片發送給WEB瀏覽器
        /// 〈/summary>
        /// 〈param name="context">〈/param>
        public void ProcessRequest(HttpContext context)
        {
            int size = AuthCode.mySize; //Int32.Parse((String)context.Session["Size"]);
            MemoryStream ms = new MemoryStream(); //  建立記憶體流(初始長度為0 自動擴充)
            string NumStr = GetRandomNumberString(size);// 獲得驗證碼字元
            context.Session.Add("value", NumStr);//將驗證碼字元儲存到session裡面
            Bitmap theBitmap = CreateImage(NumStr);// 獲得驗證碼圖片
            theBitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);//將位元影像寫入記憶體流
            context.Response.ClearContent();  //清除緩衝區裡的所有內容輸出
            context.Response.ContentType = "image/jpeg"; //需要輸出圖象資訊 要修改HTTP頭
            context.Response.BinaryWrite(ms.ToArray()); //將記憶體流寫入HTTP輸出資料流
            theBitmap.Dispose(); //釋放資源
            ms.Close();//釋放資源
            ms.Dispose();//釋放資源
            context.Response.End();
        }

  
    }
}
 

4---》產生解決方案和類庫後開啟Web表單再工具列可以看見

 

5--》拖放到web表單

〈%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default"  %>

〈%@ Register assembly="AuthCode" namespace="AuthCode" tagprefix="cc1" %>

〈!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>
        〈cc1:AuthCode ID="AuthCode1" runat="server" MySize="5" />
    〈/div>
    〈/form>
〈/body>
〈/html>

設定驗證碼字元長度

6--》在webconfig檔案添加節點

〈system.web>
〈httpHandlers>
      〈add verb="*" path="*.jd" type="AuthCode.AuthCodeHttpHander" />
〈/httpHandlers>
〈/system.web> 

7--》在瀏覽器查看

點擊可以重新整理

8--》》this.AuthCode1.GetValue() 獲得驗證碼

第一次寫技術文章還請各位博友前輩多多指教

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.