- 作用:防止惡意注冊,惡意破解密碼,惡意灌水
- 分類:用戶端驗證和伺服器端驗證。
- 關鍵問題:1,獲得一個随機生成的字元串 2,把字元串畫到網頁上。 3.比較驗證
網上的代碼很多,自己也動手模仿了一個。
- 獲得一個随機的字元串
#region 随機取得數字字母
private string GenarateCheckCode()
{
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' + number % 10);
else
code=(char)('A'+number%26);
checkCode += code.ToString();
}
Session["num"] = checkCode;
return checkCode;
}
#endregion
2.把字元串畫到網頁上
#region 把随機數字和字母畫到圖檔上
private void createCodeCheckImage(string checkCode)
{
if (checkCode == null || checkCode.Trim() == string.Empty)
return;
System.Drawing.Bitmap img = new Bitmap((Int32)Math.Ceiling(checkCode.Length*12.5),22);
System.Drawing.Graphics g = Graphics.FromImage(img);
try {
Random random=new Random();
g.Clear(Color.White);
for(int i=0;i<25;i++)
{
int x1=random.Next(img.Width);
int x2=random.Next(img.Width);
int y1=random.Next(img.Height);
int y2=random.Next(img.Height);
g.DrawLine(new Pen(Color.Silver),x1,y1,x2,y2);
}
Font font=new Font("Arial",12,FontStyle.Bold);
System.Drawing.Drawing2D.LinearGradientBrush brush=new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0,0,img.Width,img.Height),Color.Blue,Color.Red,1.2f,true);
g.DrawString(checkCode,font,brush,2,2);
for(int i=0;i<10;i++)
{
int x =random.Next(img.Width);
int y =random.Next(img.Height);
img.SetPixel(x,y,Color.FromArgb(random.Next()));
}
g.DrawRectangle(new Pen(Color.Silver),0,0,img.Width-1,img.Height-1);
System.IO.MemoryStream ms=new System.IO.MemoryStream();
img.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
Response.ClearContent();
Response.ContentType="image/Gif";
Response.BinaryWrite(ms.ToArray());
}
finally{
g.Dispose();
img.Dispose();
}
}
#endregion
3.驗證
private void checkCode()
{
string vnum = Session["num"].ToString();
Session.Abandon();
ViewState["num"] = vnum;
if (this.TextBox1.Text == ViewState["num"].ToString())
{
Response.Write("<script>alert('驗證碼正确!')</script>");
return;
}
else
{
Response.Write("<script>alert('驗證碼錯誤!')</script>");
return;
}
}
了解了這三個關鍵點,我想,圖形驗證碼的編寫也可以自己勝任了。感謝網友的分享。
轉載于:https://www.cnblogs.com/snidget/archive/2011/02/10/1950654.html