ASP.NET實現(xiàn)圖形驗證碼功能
ASP.NET 實現(xiàn)圖形驗證碼能夠增強(qiáng)網(wǎng)站安全性,防止機(jī)器人攻擊。通過生成隨機(jī)驗證碼并將其繪制成圖像,用戶在輸入驗證碼時增加了人機(jī)交互的難度。本文介紹了如何使用 C# 和 ASP.NET 創(chuàng)建一個簡單而有效的圖形驗證碼系統(tǒng),包括生成隨機(jī)驗證碼、繪制驗證碼圖像以及將圖像輸出到客戶端等步驟。這種驗證碼系統(tǒng)對于保護(hù)網(wǎng)站免受惡意攻擊和機(jī)器人惡意行為具有重要意義。
一、實現(xiàn)思路
我們需要實現(xiàn)一個防爬蟲的可以動態(tài)刷新的隨機(jī)驗證碼圖片。
比如下面這種:
關(guān)鍵點:
- 動態(tài):每次打開頁面驗證碼是變化的,并且驗證碼在一些事件下會自發(fā)刷新成新的驗證碼,比如在點擊、輸入錯誤、頁面停靠超時等事件觸發(fā)時,驗證碼自動刷新。
- 隨機(jī):里面的數(shù)字和字母是隨機(jī)的,是一種強(qiáng)密碼,不容易被暴力破解。
- 防爬:防止爬蟲通過一些AI識別直接通過,我們需要增加圖片的復(fù)雜度,例如添加一些干擾性的圖案,包括但不限于噪音線、噪點等。
驗證碼生成成功后,我們還需要將驗證碼保存到 Session 中,以便后續(xù)驗證。
二、編寫前端代碼
思路已經(jīng)明確,下面,我們來構(gòu)建圖形驗證碼的前端代碼。
前端代碼包含 HTML 和 JavaScript 代碼。
1、編寫HTML代碼
HTML代碼包含一個簡單的驗證碼輸入框和刷新圖片按鈕的用戶界面:
<div class="checkcode"> <input type="text" runat="server" id="VercodeText" placeholder="驗證碼" maxlength="4"> <img onclick="changepic(this)" src="/handlers/VerCode.ashx" /> </div>
- <div class="checkcode">:創(chuàng)建一個包含驗證碼元素的 div 容器,用于樣式控制。
- <input type="text" runat="server" id="VercodeText" placeholder="驗證碼" maxlength="4">:添加一個文本輸入框,用于用戶輸入驗證碼。設(shè)置了ID為 "VercodeText",最大長度為4,同時提供了占位符 "驗證碼"。
- <img οnclick="changepic(this)" src="/handlers/VerCode.ashx" />:插入一個圖片元素,其 src 屬性指向驗證碼處理器 VerCode.ashx。當(dāng)用戶點擊該圖片時,觸發(fā)JavaScript函數(shù) changepic 進(jìn)行驗證碼圖像的刷新。
通過這樣的HTML結(jié)構(gòu),用戶可以在輸入框中輸入驗證碼,并通過點擊圖片刷新驗證碼圖像,提供了一種交互式的驗證碼體驗。
2、創(chuàng)建JavaScript函數(shù)
創(chuàng)建 changepic 函數(shù)方法:
function changepic(obj) { var timestamp = (new Date().getTime()) / 1000; $(obj).attr('src', 'VerCode.ashx?tims=' + timestamp); }
changepic 函數(shù)用于刷新驗證碼圖片,通過在 URL 中添加時間戳的方式,確保每次請求都是唯一的,避免瀏覽器緩存。
三、編寫后端代碼
后端代碼我們采用C#實現(xiàn)。
1、創(chuàng)建輸出圖形驗證碼的接口
創(chuàng)建C#驗證碼處理器 VerCode.ashx:
using CarRental.Common; using System; using System.Drawing; using System.IO; using System.Web; namespace Handlers { public class VerCode : IHttpHandler, System.Web.SessionState.IRequiresSessionState { public void ProcessRequest(HttpContext context) { } public bool IsReusable { get { return false; } } } }
VerCode 類實現(xiàn)了 IHttpHandler 接口,用于處理 HTTP 請求。
2、創(chuàng)建驗證碼生成方法
/// <summary> /// 隨機(jī)構(gòu)建驗證碼方法 /// </summary> /// <returns>返回驗證碼字符串</returns> public string CreateCode() { char code; string checkCode = string.Empty; Random rd = new Random(); for (int i = 0; i < 4; i++) { int num = rd.Next(); int _temp; if (num % 2 == 0) { _temp = ('0' + (char)(num % 10)); if (_temp == 48 || _temp == 49) { _temp += rd.Next(2, 9); } } else { _temp = ('A' + (char)(num % 10)); if (rd.Next(0, 2) == 0) { _temp = (char)(_temp + 32); } if (_temp == 66 || _temp == 73 || _temp == 79 || _temp == 108 || _temp == 111) { _temp++; } } code = (char)_temp; checkCode += code; } return checkCode; }
CreateCode 方法用于生成隨機(jī)驗證碼,包含數(shù)字和字母,并進(jìn)行了一些特殊字符的處理,以增加驗證碼的復(fù)雜性。
3、 繪制驗證碼圖片
① 配置驗證碼參數(shù)
我們先定義驗證碼圖像的寬度、高度、字體大小以及用于生成隨機(jī)數(shù)的 Random 對象。
int codeWeight = 80; int codeHeight = 22; int fontSize = 16; Random rd = new Random();
② 生成驗證碼字符串
這一步很簡單,我們直接調(diào)用之前寫好的 CreateCode 方法。
string checkCode = CreateCode();
③ 構(gòu)建驗證碼背景
創(chuàng)建一個位圖對象,并在其上創(chuàng)建圖形對象,然后用白色填充圖像背景。
Bitmap image = new Bitmap(codeWeight, codeHeight); Graphics g = Graphics.FromImage(image); g.Clear(Color.White);
④ 畫噪音線
在圖像上繪制兩條隨機(jī)顏色的噪音線,增加驗證碼的復(fù)雜性。
for (int i = 0; i < 2; i++) { int x1 = rd.Next(image.Width); int x2 = rd.Next(image.Width); int y1 = rd.Next(image.Height); int y2 = rd.Next(image.Height); g.DrawLine(new Pen(color[rd.Next(color.Length)]), new Point(x1, y1), new Point(x2, y2)); }
⑤ 畫驗證碼
使用循環(huán)逐個繪制驗證碼字符串中的字符,每個字符使用隨機(jī)顏色和字體。
for (int i = 0; i < checkCode.Length; i++) { Color clr = color[rd.Next(color.Length)]; Font ft = new Font(font[rd.Next(font.Length)], fontSize); g.DrawString(checkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 18 + 2, 0); }
⑥ 畫噪音點
在圖像上繪制100個隨機(jī)顏色的噪音點,增加驗證碼的隨機(jī)性。
for (int i = 0; i < 100; i++) { int x = rd.Next(image.Width); int y = rd.Next(image.Height); image.SetPixel(x, y, Color.FromArgb(rd.Next())); }
⑦ 畫邊框線
在圖像周圍繪制銀色邊框線,使驗證碼更加清晰。
g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
⑧ 將驗證碼圖像保存到內(nèi)存流
將生成的驗證碼圖像保存到內(nèi)存流中,準(zhǔn)備輸出到客戶端。
MemoryStream ms = new MemoryStream(); image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
⑨ 將驗證碼保存到Session中
將生成的驗證碼字符串保存到Session中,以便后續(xù)驗證。
context.Session[ConstantValues.VerCodeSessionName] = checkCode;
⑩ 輸出圖像到客戶端
配置HTTP響應(yīng),將驗證碼圖像輸出到客戶端。
context.Response.ContentType = "Image/Gif"; context.Response.ClearContent(); context.Response.BinaryWrite(ms.ToArray());
最后,別忘記釋放圖像和圖形資源,防止內(nèi)存泄漏。
finally { image.Dispose(); g.Dispose(); }
4、完整后端代碼
完整的 VerCode.cs 代碼如下:
using TestMoudle.Common; using System; using System.Drawing; using System.IO; using System.Web; namespace Handlers { public class VerCode : IHttpHandler, System.Web.SessionState.IRequiresSessionState { public void ProcessRequest(HttpContext context) { int codeWeight = 80; int codeHeight = 22; int fontSize = 16; Random rd = new Random(); string checkCode = CreateCode(); //構(gòu)建驗證碼字符串 Bitmap image = new Bitmap(codeWeight, codeHeight); //構(gòu)建畫圖 Graphics g = Graphics.FromImage(image); //構(gòu)建畫布 g.Clear(Color.White); //清空背景色 Color[] color = new Color[] { Color.Red, Color.Black, Color.Green, Color.Blue }; string[] font = new string[] { "宋體", "黑體", "楷體" }; //畫噪音線 for (int i = 0; i < 2; i++) { int x1 = rd.Next(image.Width); int x2 = rd.Next(image.Width); int y1 = rd.Next(image.Height); int y2 = rd.Next(image.Height); g.DrawLine(new Pen(color[rd.Next(color.Length)]), new Point(x1, y1), new Point(x2, y2)); } //畫驗證碼 for (int i = 0; i < checkCode.Length; i++) { Color clr = color[rd.Next(color.Length)]; Font ft = new Font(font[rd.Next(font.Length)], fontSize); g.DrawString(checkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 18 + 2, 0); } //畫噪音點 for (int i = 0; i < 100; i++) { int x = rd.Next(image.Width); int y = rd.Next(image.Height); image.SetPixel(x, y, Color.FromArgb(rd.Next())); } //畫邊框線 g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); MemoryStream ms = new MemoryStream(); try { image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); context.Session[ConstantValues.VerCodeSessionName] = checkCode; //將驗證碼保存到Session中 context.Response.ContentType = "Image/Gif"; context.Response.ClearContent(); context.Response.BinaryWrite(ms.ToArray()); } finally { image.Dispose(); g.Dispose(); } } public bool IsReusable { get { return false; } } } }
四、測試效果
我們運行項目,可以看到驗證碼圖像順利生成了,并且點擊可以刷新圖片內(nèi)容。
到此這篇關(guān)于ASP.NET實現(xiàn)圖形驗證碼的文章就介紹到這了,更多相關(guān)ASP.NET圖形驗證碼內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
asp.net web頁面元素的多語言化(多國語化)實現(xiàn)分享
開發(fā)的一些系統(tǒng),經(jīng)常要求支持多語言(例如日文,英文等),接下來介紹如何實現(xiàn)asp.net開發(fā)中web頁面實現(xiàn)頁面元素的多語言化(多國語化)感興趣的朋友可以了解下,或許對你學(xué)習(xí)有所幫助2013-02-02開啟SQLSERVER數(shù)據(jù)庫緩存依賴優(yōu)化網(wǎng)站性能
2010-04-04Asp.Net 網(wǎng)站優(yōu)化系列之?dāng)?shù)據(jù)庫優(yōu)化 分字訣 分表(縱向拆分,橫向分區(qū))
上篇談了分庫,這一篇我們來分表2010-06-06如何對ASP.NET網(wǎng)站實現(xiàn)靜態(tài)化
對于訪問量比較大的網(wǎng)站,網(wǎng)頁靜態(tài)化是一個比較可靠的解決方案。靜態(tài)化將顯著降低服務(wù)器的壓力,提升服務(wù)器處理能力。下面將介紹兩種不同的實現(xiàn)方法,并進(jìn)行對比。2015-09-09