在ASP.NET下實現數字和字元相混合的驗證碼(C# Code)
來源:互聯網
上載者:User
asp.net|驗證碼 為了便於大家學習,修改vb.net code成為c#
gif.aspx檔案修改的內容
private void Page_Load(object sender, System.EventArgs e)
{
// 在此處放置使用者代碼以初始化頁面
//RndNum是一個自訂函數
string VNum = RndNum(5);
Session["VNum"] = VNum;
ValidateCode(VNum);
}
private void ValidateCode(string VNum)
{
//產生驗證code
System.Drawing.Bitmap img;
System.Drawing.Graphics g;
System.IO.MemoryStream ms;
int gheight = Convert.ToInt32(VNum.Length*11.5);
//gheight為圖片寬度,根據字元長度自動更改圖片寬度
img = new Bitmap(gheight,20);
g = Graphics.FromImage(img);
//在矩形內繪製字串(字串,字型,畫筆顏色,左上x.左上y)
g.DrawString(VNum,new Font("Arial",10),new SolidBrush(System.Drawing.Color.Blue),3,3);
ms = new MemoryStream();
img.Save(ms,ImageFormat.Png);
Response.ClearContent(); //需要輸出圖象資訊 要修改HTTP頭
Response.ContentType = "image/gif";
Response.BinaryWrite(ms.ToArray());
g.Dispose();
img.Dispose();
Response.End();
}
//'函數名稱:RndNum
//'函數參數:VcodeNum--設定返回隨機字串的位元
//'函數功能:產生數字和字元混合的隨機字串
private string RndNum(int VcodeNum)
{
string Vchar = "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,W,X,Y,Z" ;
string[] VcArray = Vchar.Split(",".ToCharArray()); //將字串產生數組
string VNum = "";
int i;
for(i=1;i<VcodeNum;i++)
{
System.Random ro = new Random();
double decA = ro.NextDouble();
VNum = VNum + VcArray[Convert.ToInt32(35*decA)];
}
// For i=1 to VcodeNum
//Randomize
//VNum=VNum & VcArray(Int(35*Rnd)) '數組一般從0開始讀取,所以這裡為35*Rnd
//Next
return VNum;
}
ValidateCode.aspx修改內容
private void Page_Load(object sender, System.EventArgs e)
{
// 在此處放置使用者代碼以初始化頁面
string VNum;
if(Session["VNum"]!= null)
{
VNum = Session["VNum"].ToString();
Session.Abandon();
ViewState["VNum"]=VNum;
}
}
private void Button1_Click(object sender, System.EventArgs e)
{
if(txtValidateCode.Text == ViewState["VNum"].ToString() )
{
lblShow.Text="提示:驗證通過" ;
}
else
{
lblShow.Text="所填寫的驗證碼與所給的不符";
}
}