在做管理系統時候,我們時常要使用驗證碼對用戶的一些操作進行驗證,增加系統的安全性。以下是asp.net中生成驗證碼的部分。個人覺得使用原生態的httpHandler文件生成驗證碼比使用.aspx文件生成驗證碼要好很多,.aspx文件中。page類是一個很大的類。page類也實現了IHttpHandler接口。
新建一個一般處理程序文件Code.ashx,在裏面加入如下代碼。
public class Handler : IHttpHandler,System.Web.SessionState.IRequiresSessionState
{
///生成隨機驗證碼
public string GetCode(int number)
{
string s = "0AaB1oCb3pqD2cErf4dFs5GetHI6gu7JKLvhMwNixO8PyQj9zRSkTUVlWmXYnZ";
Random rand=new Random();
StringBuilder code=new StringBuilder();
for(int i=0;i<number;i++)
{
char word=s[rand.Next(s.Length)];
code.Append(word.ToString());
}
return code.ToString();
}
///.httpHandler文件請求入口函數,context表示當前請求的上下文信息(或者成爲當前請求的環境)
public void Proce***equest(HttpContext context)
{
string code = GetCode(4);//獲取長度爲4的隨機驗證碼
context.Session["Code"] = code;
Bitmap Image = new Bitmap(120, 40);
Graphics g = Graphics.FromImage(Image);
try
{
g.Clear(Color.White);//清除背景色
Random rand = new Random();
for (int i = 0; i < 30; i++)//畫噪線
{
int x1 = rand.Next(Image.Width);
int x2 = rand.Next(Image.Width);
int y1 = rand.Next(Image.Height);
int y2 = rand.Next(Image.Height);
g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);//指定畫筆,指定矩形中 畫線的起始點和終點座標
}
Font font = new Font("Arial", 20, FontStyle.Italic);///聲明字體
//畫刷,第一個參數指定畫刷作用範圍矩形,第二個參數表示起始位置顏色,第三個參數表示表示終止位置顏色,第四個表示偏離角度,第五個表示是否顏色漸變
LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, Image.Width, Image.Height), Color.Blue, Color.DarkRed, 5, true);
g.DrawString(code, font, brush, 3, 2);
g.DrawRectangle(new Pen(Color.Silver), 0, 0, Image.Width - 1, Image.Height - 1);
System.IO.MemoryStream stream = new System.IO.MemoryStream();
Image.Save(stream, ImageFormat.Gif);
context.Response.Clear();//清空Response中的數據緩存
context.Response.ContentType = "p_w_picpath/Gif";
context.Response.BinaryWrite(stream.ToArray());//輸出內存流
}
finally
{
g.Dispose();
Image.Dispose();
}
}
public bool IsReusable {
get {
return false;
}
}
}
在客戶端頁面,我們使用原生態的html標籤生成驗證碼,使用<img>標籤即可,如下
<img src="Handler.ashx" alt="單擊圖片換一個驗證碼." style="cursor: pointer" onclick="this.src='Code.ashx?date='+new Date()" />
在<img>標籤中的onclick事件中我們使用javascript改變img標籤的src屬性,沒單擊一次,<img>就會重新請求一次Code.ashx文件,因爲new Date()總是獲取當前時間,沒單擊一次this.src後面的date參數都會變化,瀏覽器就會認爲這是一個新的網址,進而重新請求一次。(如果網址後沒有?date=new Date(),瀏覽器將不會請求,也就是說驗證碼不會變化)。