ASP.NET1.1驗證碼產生的原理及應用
ASP.NET1.1驗證碼實現原理
通過隨機函數產生驗證碼元素,將數值型的驗證碼元素轉換成字符型然后再連成字符串,將驗證碼字符串寫入Cookie以供驗證時調用。
通過后臺動態繪制位圖的方法,繪制一個指定大小的位圖,然后在空白位圖畫出底紋、驗證碼字體、和邊框。
ASP.NET1.1驗證碼實現代碼
(1)Login.aspx(登錄頁前臺)
- < %@ Page language="c#" Codebehind="Login.aspx.cs" AutoEventWireup="false" Inherits="Validator.Login" %>
- < !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
- < HTML>
- < HEAD>
- < title>Login< /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">
- < asp:button id="Button1" style="Z-INDEX: 101; LEFT: 128px; POSITION: absolute; TOP: 64px" runat="server"
- Width="96px" Text="提交">< /asp:button>
- < IMG src="CheckCode.aspx">
- < asp:label id="lblMessage" style="Z-INDEX: 102; LEFT: 16px; POSITION: absolute; TOP: 128px"
- runat="server">< /asp:label>
- < asp:textbox id="txtCheckCode" style="Z-INDEX: 103; LEFT: 16px; POSITION: absolute; TOP: 64px"
- runat="server" Width="88px">< /asp:textbox>
- < /form>
- < /body>
- < /HTML>
(2)Login.aspx.cs(登錄頁后臺)
- using System;
- using System.Collections;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Web;
- using System.Web.SessionState;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Web.UI.HtmlControls;
- namespace Validator
- {
- /**//// < summary>
- /// Login 的摘要說明。
- /// < /summary>
- public class Login : System.Web.UI.Page
- {
- protected System.Web.UI.WebControls.Button Button1;
- protected System.Web.UI.WebControls.Label lblMessage;
- protected System.Web.UI.WebControls.TextBox txtCheckCode;
- private void Page_Load(object sender, System.EventArgs e)
- {
- // 在此處放置用戶代碼以初始化頁面
- }
- Web 窗體設計器生成的代碼#region Web 窗體設計器生成的代碼
- override protected void OnInit(EventArgs e)
- {
- //
- // CODEGEN: 該調用是 asp.net Web 窗體設計器所必需的。
- //
- InitializeComponent();
- base.OnInit(e);
- }
- /**//// < summary>
- /// 設計器支持所需的方法 - 不要使用代碼編輯器修改
- /// 此方法的內容。
- /// < /summary>
- private void InitializeComponent()
- {
- this.Button1.Click += new System.EventHandler(this.Button1_Click);
- this.Load += new System.EventHandler(this.Page_Load);
- }
- #endregion
- private void Button1_Click(object sender, System.EventArgs e)
- {
- if(Request.Cookies["CheckCode"] == null)
- {
- lblMessage.Text = "您的瀏覽器設置已被禁用 Cookies,您必須設置瀏覽器允許使用 Cookies 選項后才能使用本系統。";
- lblMessage.Visible = true;
- return;
- }
- if(String.Compare(Request.Cookies["CheckCode"].Value, txtCheckCode.Text, false) != 0) //參數為false時為區分大小寫
- {
- lblMessage.Text = "驗證碼錯誤,請輸入正確的驗證碼。";
- lblMessage.Visible = true;
- return;
- }
- else
- {
- lblMessage.Text = "通過驗證";
- lblMessage.Visible = true;
- return;
- }
- }
- }
- }
(3) CheckCode.aspx(驗證頁前臺)
- < %@ Page language="c#" Codebehind="CheckCode.aspx.cs" AutoEventWireup="false" Inherits="Validator.CheckCode" %>
- < !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
- < html>
- < head>
- < title>CheckCode< /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">
- < FONT face="宋體">< /FONT>
- < /form>
- < /body>
- < /html>
(4)CheckCode.aspx.cs(驗證頁后臺)
- using System;
- using System.Collections;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Web;
- using System.Web.SessionState;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Web.UI.HtmlControls;
- namespace Validator
- {
- /**//// < summary>
- /// CheckCode 的摘要說明。
- /// < /summary>
- public class CheckCode : System.Web.UI.Page
- {
- private void Page_Load(object sender, System.EventArgs e)
- {
- // 在此處放置用戶代碼以初始化頁面
- this.CreateCheckCodeImage(GenerateCheckCode());
- }
- Web 窗體設計器生成的代碼#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
- private string GenerateCheckCode()
- {
- int number;
- char code;
- string checkCode = String.Empty;
- System.Random random = new Random();
- for(int i=0; i< 5; i++)
- { //隨機產生一個整數
- number = random.Next();
- //如果隨機數是偶數 取余選擇從[0-9]
- if(number % 2 == 0)
- code = (char)('0' + (char)(number % 10));
- else
- //如果隨機數是奇數 選擇從[A-Z]
- code = (char)('A' + (char)(number % 26));
- checkCode += code.ToString();
- }
- Response.Cookies.Add(new HttpCookie("CheckCode", checkCode));
- return checkCode;
- }
- //建立一個隨機圖形
- private void CreateCheckCodeImage(string checkCode)
- {
- if(checkCode == null || checkCode.Trim() == String.Empty)
- return;
- //建立一個位圖文件 確立長寬
- System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);
- Graphics g = Graphics.FromImage(image);
- try
- {
- //生成隨機生成器
- Random random = new Random();
- //清空圖片背景色
- g.Clear(Color.White);
- //畫圖片的背景噪音點
- for(int i=0; i< 60; i++)
- {
- int x = random.Next(image.Width);
- int y = random.Next(image.Height);
- image.SetPixel(x, y, Color.FromArgb(random.Next()));
- }
- //把產生的隨機數以字體的形式寫入畫面
- Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
- System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
- g.DrawString(checkCode, font, brush, 2, 2);
- //畫圖片的邊框線
- 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());
- }
- finally
- {
- g.Dispose();
- image.Dispose();
- }
- }
- }
- }
ASP.NET1.1驗證碼主要函數分析
1、通過隨機函數(Random)先產生驗證碼組成元素(這里為五位) 并將其轉換為字符串(屬性為只讀),完成后寫入“Cookie”中去以供驗證時調用。
2、將驗證碼字符串寫入圖形:
(1)建立一個位圖文件確定長和寬:
- System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);
(a)System.Drawing. [C#] Bitmap(int width,int height);
(b)double Math.Ceiling (double a):返回大于或等于指定數字的最小整數。
(2)畫圖片的背景噪音點(60個):
- for(int i=0; i< 60; i++) {
- int x = random.Next(image.Width);
- int y = random.Next(image.Height);
- image.SetPixel(x, y, Color.FromArgb(random.Next()));
- }
(a) public virtual int Next(int maxValue);返回一個小于所指定***值的非負隨機數。 參數:maxValue-要生成的隨機數的上限。maxValue 必須大于或等于零。
(b) image.SetPixel(int x,int y,Color color); 參數: x-要設置的像素的 x 坐標;y-要設置的像素的 y 坐標;color-Color 結構,它表示要分配給指定像素的顏色。
(c) Color.FromArgb(int argb) 參數:argb-指定 32 位 ARGB 值的值。
(3)把產生的隨機數以字體的形式寫入位圖:Graphics.DrawString(string s,Font font,Brush brush,float x,float y);
參數:s-要繪制的字符串;font-Font 對象,它定義字符串的文本格式;
brush-Brush 對象,它確定所繪制文本的顏色和紋理;
x-所繪制文本的左上角的 x 坐標;
y-所繪制文本的左上角的 y 坐標。(在指定位置并且用指定的 Brush 和 Font 對象繪制指定的文本字符串)
(4) 畫圖片的邊框線: public void DrawRectangle(Pen pen, int x, int y, int width, int height);繪制由坐標對、寬度和高度指定的矩形。
參數:pen-Pen 對象,它確定矩形的顏色、寬度和樣式;
x-要繪制的矩形的左上角的 x 坐標;
y-要繪制的矩形的左上角的 y 坐標;
width-要繪制的矩形的寬度;height-要繪制的矩形的高度。
(5) 將圖片以二進制流的方式輸出加上格式并可顯示出來。
以上就是asp.net1.1中驗證碼產生的原理及其應用。【編輯推薦】