C# ASP.NET 驗證碼

來源:互聯網
上載者:User

標籤:codec   lin   程式   使用   img   buffer   stream   mat   []   

使用C# ASP.NET 擷取 驗證碼的代碼書寫

一般都採用非同步 點擊 前台驗證碼圖片 請求一次 :

前台圖片代碼:

<img id="imgvalidatecode" src="../ashx/validatecode.ashx" alt="點擊重新整理" style="vertical-align: middle;" />

服務端一般處理常式:   ValidateCode.ashx

public class ashx_ValidateCode : BaseHttpHandlerNo{    public override void ProcessRequest(HttpContext context)    {        base.ProcessRequest(context);        //設定頁面不被緩衝        Response.Buffer = true;        Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1);        Response.Expires = 0;        Response.CacheControl = "no-cache";        Response.AppendHeader("Pragma", "No-Cache");        string checkCode =ValidateCode.GetRandomCode(4);        Session["CheckCode"] = checkCode;        ValidateCode.CreateImage(checkCode,Response);    }}

注意:ValidateCode.GetRandomCode(4)  為擷取驗證碼的主要方法。

下面就來貼出此ValidateCode類的代碼:

public static string GetRandomCode(int codeCount)    {        string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,M,N,P,Q,R,S,T,U,W,X,Y,Z";        string[] allCharArray = allChar.Split(‘,‘);        string randomCode = "";        int temp = -1;        Random rand = new Random();        for (int i = 0; i < codeCount; i++)        {            if (temp != -1)            {                rand = new Random(temp * i * ((int)DateTime.Now.Ticks));            }            int t = rand.Next(33);            while (temp == t)            {                t = rand.Next(33);            }            temp = t;            randomCode += allCharArray[t];        }        return randomCode;    }    public static void CreateImage(string checkCode,HttpResponse response)    {        int iwidth = (int)(checkCode.Length * 14);        System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 20);        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);        System.Drawing.Font f = new System.Drawing.Font("Arial ", 10);//, System.Drawing.FontStyle.Bold);        System.Drawing.Brush b = new System.Drawing.SolidBrush(System.Drawing.Color.Black);        System.Drawing.Brush r = new System.Drawing.SolidBrush(System.Drawing.Color.FromArgb(166, 8, 8));        //g.FillRectangle(new System.Drawing.SolidBrush(Color.Blue), 0, 0, image.Width, image.Height);        //g.Clear(Color.AliceBlue);//背景色        g.Clear(System.Drawing.ColorTranslator.FromHtml("#99C1CB"));//背景色        char[] ch = checkCode.ToCharArray();        for (int i = 0; i < ch.Length; i++)        {            if (ch[i] >= ‘0‘ && ch[i] <= ‘9‘)            {                //數字用紅色顯示                g.DrawString(ch[i].ToString(), f, r, 3 + (i * 12), 3);            }            else            {   //字母用黑色顯示                g.DrawString(ch[i].ToString(), f, b, 3 + (i * 12), 3);            }        }        //for迴圈用來產生一些隨機的水平線                    Pen blackPen = new Pen(Color.Black, 0);                    Random rand = new Random();                    for (int i=0;i<2;i++)                    {                        int y = rand.Next(image.Height);                        g.DrawLine(blackPen,0,y,image.Width,y);                    }        System.IO.MemoryStream ms = new System.IO.MemoryStream();        image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);        //history back 不重複         response.Cache.SetNoStore();//這一句                 response.ClearContent();        response.ContentType = "image/Jpeg";        response.BinaryWrite(ms.ToArray());        g.Dispose();        image.Dispose();    }

是不是很簡單~   中間不想要 水平線 就注釋掉好了!

C# ASP.NET 驗證碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.