2012年4月18日 星期三

[.NET]圖片驗證防止灌水機器人

而圖片驗證碼其運作原理相當的簡單,其運作原理則是先隨機產生一組流水號,並寫入在session中,再利用繪圖指令,將流水號繪製到圖片中,因此即便從原始碼或是對著圖片按右鍵時,也完全無法得知此圖片的數字,因此在谷哥中找到個小範例,並稍作了一些修改,現在就來剖析圖片驗證碼的製作吧!
Step1
分別從工具箱中拖拉出,圖片TextBoxLabel文字按鈕元件..等,再將這些元件的ID命名如下。

Step2
新增一個ValidateCode.ashx檔,並複製下方的Code碼貼入。
ValidateCode.ashx的code
public void ProcessRequest(HttpContext context)
{
CreateCheckCodeImage(GenerateCheckCode(context), context);
}
private string GenerateCheckCode(HttpContext context)
{
int number;
char code;
string checkCode = String.Empty;
System.Random random = new Random();
for (int i = 0; i < 5; i++)
{
number = random.Next();
if (number % 2 == 0)
code = (char)('0' + (char)(number % 10));
else
code = (char)('A' + (char)(number % 26));
checkCode += code.ToString();
}
//儲存在cookie
// context.Response.Cookies.Add(new HttpCookie(
"CheckCode", checkCode));
//儲存在session
context.Session["CheckCode"] = checkCode;
return checkCode;
}
private void CreateCheckCodeImage(string checkCode,
HttpContext context)
{
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);
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.Black, Color.Black, 1.2f, true);
g.DrawString(checkCode, font, brush, 2, 2);
//圖片邊框
g.DrawRectangle(new Pen(Color.Black),
0, 0, image.Width - 1, image.Height - 1);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
context.Response.ClearContent();
context.Response.ContentType = "image/Gif";
context.Response.BinaryWrite(ms.ToArray());
}
finally
{
g.Dispose();
image.Dispose();
}
}
public bool IsReusable
{
get
{return false;}}

Step3
對著圖片點一下,並將圖片的ImageUrl設為ValidateCode.ashx

Step4
雙響Check按鈕,再複製下方的Code並貼入
protected void CheckBt_Click(object sender, EventArgs e)
if (String.Compare(Session["CheckCode"].ToString(), this.TextBox1.Text, true) == 0)
{
CheckCode1.Text = "正確";
}
else
{
CheckCode1.Text = "驗證碼錯誤";

沒有留言:

張貼留言