利用ASP.NET的泛型處理常式(Handler)產生圖片驗證碼,結合IRequiresSessionState將驗證碼儲存在session裡,透過session值來驗證

利用ASP.NET的泛型處理常式(Handler)產生圖片驗證碼,結合IRequiresSessionState將驗證碼儲存在session裡,透過session值來驗證

最近小舖有人提到圖片驗證碼的文章.....

一般在輸入表單裡加上圖片驗證碼是不錯的...可以防止一些攻擊....

一般圖片驗證碼都是寫在aspx裡,而且都是利用cookie儲存....

小弟用一個簡單的範例,,介紹如何將圖片驗碼碼寫在handle裡,,並且將驗證碼儲存在session裡....

此範例,包含cookie與session的用法..,驗證碼的程式是參考網路上別人寫好的code...c#範例


ValidateCode.ashx

001 <%@ WebHandler Language="C#" Class="ValidateCode" %>
002
003 <%@ WebHandler Language="C#" Class="ValidateCode" %>
004
005 using System;
006 using System.Web;
007 using System.Drawing;
008 using System.Web.SessionState;

009
010 public class ValidateCode : IHttpHandler, IRequiresSessionState
011 {
012
013     public void ProcessRequest(HttpContext context)
014     {
015         CreateCheckCodeImage(GenerateCheckCode(context), context);
016     }

017
018     private string GenerateCheckCode(HttpContext context)
019     {
020         int number;
021         char code;
022         string checkCode = String.Empty;
023
024         System.Random random = new Random();
025
026         for (int i = 0; i < 5; i++)
027         {
028             number = random.Next();
029
030             if (number % 2 == 0)
031                 code = (char)('0' + (char)(number % 10));
032             else
033                 code = (char)('A' + (char)(number % 26));
034
035             checkCode += code.ToString();
036         }

037
038         //儲存在cookie
039         context.Response.Cookies.Add(new HttpCookie("CheckCode", checkCode));
040
041         //儲存在session
042         context.Session["CheckCode"] = checkCode;
043
044         return checkCode;
045     }

046
047     private void CreateCheckCodeImage(string checkCode, HttpContext context)
048     {
049         if (checkCode == null || checkCode.Trim() == String.Empty)
050             return;
051
052         System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);
053         Graphics g = Graphics.FromImage(image);
054
055         try
056         {
057             //生成?机生成器
058             Random random = new Random();
059
060             //清空?片背景色
061             g.Clear(Color.White);
062
063             //??片的背景噪音?
064             for (int i = 0; i < 25; i++)
065             {
066                 int x1 = random.Next(image.Width);
067                 int x2 = random.Next(image.Width);
068                 int y1 = random.Next(image.Height);
069                 int y2 = random.Next(image.Height);
070
071                 g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
072             }

073
074             Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
075             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);
076             g.DrawString(checkCode, font, brush, 2, 2);
077
078             //??片的前景噪音?
079             for (int i = 0; i < 100; i++)
080             {
081                 int x = random.Next(image.Width);
082                 int y = random.Next(image.Height);
083
084                 image.SetPixel(x, y, Color.FromArgb(random.Next()));
085             }

086
087             //??片的?框?
088             g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
089
090             System.IO.MemoryStream ms = new System.IO.MemoryStream();
091             image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
092             context.Response.ClearContent();
093             context.Response.ContentType = "image/Gif";
094             context.Response.BinaryWrite(ms.ToArray());
095         }

096         finally
097         {
098             g.Dispose();
099             image.Dispose();
100         }

101     }

102
103     public bool IsReusable
104     {
105         get
106         {
107             return false;
108         }

109     }

110
111 }

112


CheckCode.aspx

01 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="CheckCode.aspx.cs" Inherits="CheckCode" %>
02
03 <%@ Register Src="ValidateCode.ascx" TagName="ValidateCode" TagPrefix="uc1" %>
04 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
05 <html xmlns="http://www.w3.org/1999/xhtml">
06 <head id="Head1" runat="server">
07     <title>CheckCode</title>
08 </head>
09 <body>
10     <form id="form1" runat="server">
11         <div>
12             <asp:Image ID="Image1" runat="server" ImageUrl="ValidateCode.ashx" /><br />
13             <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
14             <br />
15             <asp:Button ID="Button1" runat="server" Text="CheckCode(cookie)" OnClick="Button1_Click" /><br />
16             <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="CheckCode(Session)" /></div>
17     </form>
18 </body>
19 </html>
20


CheckCode.aspx.cs

01 using System;
02 using System.Data;
03 using System.Configuration;
04 using System.Collections;
05 using System.Web;
06 using System.Web.Security;
07 using System.Web.UI;
08 using System.Web.UI.WebControls;
09 using System.Web.UI.WebControls.WebParts;
10 using System.Web.UI.HtmlControls;

11
12 public partial class CheckCode : System.Web.UI.Page
13 {
14     protected void Page_Load(object sender, EventArgs e)
15     {
16
17     }

18     protected void Button1_Click(object sender, EventArgs e)
19     {
20         //利用cookie驗證
21         if (String.Compare(Request.Cookies["CheckCode"].Value, this.TextBox1.Text, true) == 0)
22         {
23             Response.Write("正確");
24         }

25         else
26         {
27             Response.Write("錯誤");
28         }

29     }

30     protected void Button2_Click(object sender, EventArgs e)
31     {
32         //利用session驗證
33         if (String.Compare(Session["CheckCode"].ToString(), this.TextBox1.Text, true) == 0)
34         {
35             Response.Write("正確");
36         }

37         else
38         {
39             Response.Write("錯誤");
40         }

41     }

42 }



執行結果:


參考網址:http://www.cnblogs.com/gwazy/archive/2005/04/18/139510.html