如何使用ASP.NET實現產生驗證碼功能的執行個體代碼

來源:互聯網
上載者:User
這篇文章主要介紹了ASP.NET實現的產生驗證碼功能,結合執行個體形式較為詳細的分析了asp.net產生驗證碼的原理、步驟與相關實現技巧,並附帶demo源碼供讀者下載參考,需要的朋友可以參考下

本文執行個體講述了ASP.NET實現的產生驗證碼功能。分享給大家供大家參考,具體如下:

產生驗證碼原理:產生隨機字元,並將字元產生為圖片,同時儲存到Session裡去,然後驗證使用者輸入的內容是否與Session中的驗證碼相符即可。

:使用者可以點擊切換驗證碼資訊。

一般處理常式:CheckCodeHandler.cs


<%@ WebHandler Language="C#" Class="CheckCodeHandler" %>using System;using System.Web;using System.Text;using System.Drawing;using System.Web.SessionState;public class CheckCodeHandler : IHttpHandler,IRequiresSessionState{  //產生驗證碼的字元集  public string charcode = "2,3,4,5,6,8,9,A,B,C,D,E,F,G,H,J,K,M,N,P,R,S,U,W,X,Y,a,b,c,d,e,f,g,h,j,k,m,n,p,r,s,u,w,x,y";  public void ProcessRequest (HttpContext context) {    string validateCode = CreateRandomCode(4);    context.Session["ValidateCode"] = validateCode;//將驗證碼儲存到session中    CreateCodeImage(validateCode, context);  }  public bool IsReusable {    get {      return false;    }  }  /// <summary>  /// 產生驗證碼  /// </summary>  /// <param name="n">驗證碼個數</param>  /// <returns>驗證碼字串</returns>  public string CreateRandomCode(int n)  {    string[] CharArray = charcode.Split(',');//將字串轉換為字元數組    string randomCode = "";    int temp = -1;    Random rand = new Random();    for (int i = 0; i < n; i++)    {      if (temp != -1)      {        rand = new Random(i * temp * ((int)DateTime.Now.Ticks));      }      int t = rand.Next(CharArray.Length - 1);      if (temp != -1 && temp == t)      {        return CreateRandomCode(n);      }      temp = t;      randomCode += CharArray[t];    }    return randomCode;  }  public void CreateCodeImage(string checkCode, HttpContext context)  {    int iwidth = (int)(checkCode.Length * 13);    System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 20);    Graphics g = Graphics.FromImage(image);    Font f = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Italic | System.Drawing.FontStyle.Bold));    // 前景色彩    Brush b = new System.Drawing.SolidBrush(Color.Black);    // 背景色    g.Clear(Color.White);    // 填充文字    g.DrawString(checkCode, f, b, 0, 1);    // 隨機線條    Pen linePen = new Pen(Color.Gray, 0);    Random rand = new Random();    for (int i = 0; i < 5; i++)    {      int x1 = rand.Next(image.Width);      int y1 = rand.Next(image.Height);      int x2 = rand.Next(image.Width);      int y2 = rand.Next(image.Height);      g.DrawLine(linePen, x1, y1, x2, y2);    }    // 隨機點    for (int i = 0; i < 30; i++)    {      int x = rand.Next(image.Width);      int y = rand.Next(image.Height);      image.SetPixel(x, y, Color.Gray);    }    // 邊框    g.DrawRectangle(new Pen(Color.Gray), 0, 0, image.Width - 1, image.Height - 1);    // 輸出圖片    System.IO.MemoryStream ms = new System.IO.MemoryStream();    image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);    context.Response.ClearContent();    context.Response.ContentType = "image/jpeg";    context.Response.BinaryWrite(ms.ToArray());    g.Dispose();    image.Dispose();  }}

封裝成類庫:ValidateNumber.cs


using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Drawing;using System.Web.UI;using System.Drawing.Drawing2D;using System.IO;using System.Drawing.Imaging;/// <summary>///ValidateNumber 產生驗證碼/// </summary>public class ValidateNumber{  //產生驗證碼的字元集 (易混淆的字元去掉)  private string charcode = "2,3,4,5,6,8,9,A,B,C,D,E,F,G,H,J,K,M,N,P,R,S,U,W,X,Y,a,b,c,d,e,f,g,h,j,k,m,n,p,r,s,u,w,x,y";  /// <summary>  /// 驗證碼的最大長度  /// </summary>  public int MaxLength  {    get { return 10; }  }  /// <summary>  /// 驗證碼的最小長度  /// </summary>  public int MinLength  {    get { return 1; }  }  /// <summary>  /// 產生驗證碼  /// </summary>  /// <param name="length">指定驗證碼的長度</param>  /// <returns></returns>  public string CreateValidateNumber(int length)  {    string[] CharArray = charcode.Split(',');//將字串轉換為字元數組    string randomCode = "";    int temp = -1;    Random rand = new Random();    for (int i = 0; i < length; i++)    {      if (temp != -1)      {        rand = new Random(i * temp * ((int)DateTime.Now.Ticks));      }      int t = rand.Next(CharArray.Length - 1);      if (temp != -1 && temp == t)      {        return CreateValidateNumber(length);      }      temp = t;      randomCode += CharArray[t];    }    return randomCode;  }  /// <summary>  /// 建立驗證碼的圖片  /// </summary>  /// <param name="context">context對象</param>  /// <param name="validateNum">驗證碼</param>  public void CreateValidateGraphic(HttpContext context,string validateNum)  {    int iwidth = (int)(validateNum.Length * 14);    Bitmap image = new Bitmap(iwidth, 22);    Graphics g = Graphics.FromImage(image);    try    {      //產生隨機產生器      Random random = new Random();      //清空圖片背景色      g.Clear(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 Pen(Color.Silver), x1, y1, x2, y2);      }      Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));      LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),       Color.Blue, Color.DarkRed, 1.2f, true);      g.DrawString(validateNum, font, brush, 3, 2);      //畫圖片的前景幹擾點      for (int i = 0; i < 100; i++)      {        int x = random.Next(image.Width);        int y = random.Next(image.Height);        image.SetPixel(x, y, Color.FromArgb(random.Next()));      }      //畫圖片的邊框線      g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);      //儲存圖片資料      MemoryStream stream = new MemoryStream();      image.Save(stream, ImageFormat.Jpeg);      //輸出圖片      context.Response.Clear();      context.Response.ContentType = "image/jpeg";      context.Response.BinaryWrite(stream.ToArray());    }    finally    {      g.Dispose();      image.Dispose();    }  }  /// <summary>  /// 得到驗證碼圖片的長度  /// </summary>  /// <param name="validateNumLength">驗證碼的長度</param>  /// <returns></returns>  public static int GetImageWidth(int validateNumLength)  {    return (int)(validateNumLength * 14);  }  /// <summary>  /// 得到驗證碼圖片的高度  /// </summary>  /// <returns></returns>  public static double GetImageHeight()  {    return 22;  }}
相關文章

聯繫我們

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