雕蟲小技--自訂“驗證碼”控制項
“驗證碼”在登入的時候,經常用到,如果把“她”封裝成控制項,是不是很爽呢?但是,我一般不喜歡封裝得太厲害的“她”,因為什麼都看不到,亦或看起來比較朦朧:)
切入點
利用IHttpHandler介面,動態產生驗證碼
圖一(直接看效果吧)
看代碼吧
步驟一(建立一類庫)
Code
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Drawing;
namespace ControlValidater
{
public class CValidater:IHttpHandler,IRequiresSessionState
{
HttpResponse response = null;
HttpSessionState sessionState = null;
public void ProcessRequest(HttpContext context)
{
response = context.Response;
sessionState = context.Session;
this.GenImg(this.GenCode(4));
}
bool System.Web.IHttpHandler.IsReusable
{
get { return true; }
}
//產生隨機字串
private string GenCode(int num)
{
string[] source ={"0","1","2","3","4","5","6","7","8","9",
"A","B","C","D","E","F","G","H","I","J","K","L","M","N",
"O","P","Q","R","S","T","U","V","W","X","Y","Z"};
string code = "";
Random rd = new Random();
for (int i = 0; i < num; i++)
{
code += source[rd.Next(0, source.Length)];
}
return code;
}
//產生圖片
private void GenImg(string code)
{
Bitmap myPalette = new Bitmap(60, 20);//定義一個畫板
Graphics gh = Graphics.FromImage(myPalette);//在畫板上定義繪圖的執行個體
Rectangle rc = new Rectangle(0, 0, 60, 20);//定義一個矩形
gh.FillRectangle(new SolidBrush(Color.Silver), rc);//填充矩形
gh.DrawString(code, new Font("宋體", 16), new SolidBrush(Color.Gray), rc);//在矩形內畫出字串
myPalette.Save(response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);//將圖片顯示出來
sessionState["ValidateCode"] = code;//將字串儲存到Session中,以便需要時進行驗證
gh.Dispose();
myPalette.Dispose();
}
}
}
步驟二(使用方法)
直接引用編譯後的dll檔案
在web.config的web節點,加入<httpHandlers>元素,
例如
Code
<httpHandlers>
<add path="CValidater.aspx" verb="*" type="ControlValidater.CValidater" />
</httpHandlers>
當然,如果直接把類庫作為一個普通類,放在使用的Website的App_Data目錄的話,就不需要配置了:)
步驟三(使用方法)
在需要使用驗證碼的頁面,扔一個image標記,然後把他的url指向"類名.aspx"
例如
Code
<asp:Image ID="Image1" runat="server" ImageUrl="~/CValidater.aspx"/>
到此配置完成,是不是很簡單呢:)
哎...
還是把最後一個步驟代碼貼出來吧.
Code
protected void Button1_Click(object sender, EventArgs e)
{
string strIn = this.TextBox1.Text;
string strSess = Session["ValidateCode"].ToString();
if (strIn == strSess)
Button1.Text = "ok";
else
Button1.Text = "error";
}
需要注意的幾個地方:)
一,記得要實現IRequiresSessionState介面,雖然她只是一個標記,沒有她,Session狀態無法使用.
二,HttpSessionState的對象是通過上下文獲得的.
三,配製config的時候,不要忘記path="CValidater.aspx",如果path="*.aspx",那你所有的頁面都將被CValidater處理,這不是我們所要的.