asp.net|驗證碼
using System.Drawing;
using System.Drawing.Imaging;
private void Page_Load(object sender, System.EventArgs e)
{
// 在此處放置使用者代碼以初始化頁面
//RndNum是一個自訂函數
string VNum=RndNum(4); //這裡的數字4代表顯示的是4位的驗證字串!
Session["VNum"]=VNum;
ValidateCode(VNum);
}
//產生映像函數
private void ValidateCode(string VNum)
{
int Gheight=(int)(VNum.Length * 11.5);
//gheight為圖片寬度,根據字元長度自動更改圖片寬度
System.Drawing.Bitmap Img = new System.Drawing.Bitmap(Gheight,20);
Graphics g = Graphics.FromImage(Img);
g.DrawString(VNum,new System.Drawing.Font("Arial",10),new System.Drawing.SolidBrush(Color.Red),3,3);
//在矩形內繪製字串(字串,字型,畫筆顏色,左上x.左上y)
System.IO.MemoryStream ms=new System.IO.MemoryStream();
Img.Save(ms,System.Drawing.Imaging.ImageFormat.Png);
Response.ClearContent(); //需要輸出圖象資訊 要修改HTTP頭
Response.ContentType="image/Png";
Response.BinaryWrite(ms.ToArray());
g.Dispose();
Img.Dispose();
Response.End();
}
http://community.csdn.net/Expert/topic/3342/3342222.xml?temp=.5347406
//產生隨機數函數中從Vchar數組中隨機抽取
//字母區分大小寫
public 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(',') ;
string VNum = "" ;//由於字串很短,就不用StringBuilder了
int temp = -1 ;//記錄上次隨機數值,盡量避免生產幾個一樣的隨機數
//採用一個簡單的演算法以保證產生隨機數的不同
Random rand =new Random();
for ( int i = 1 ; i < VcodeNum+1 ; i++ )
{
if ( temp != -1)
{
rand =new Random(i*temp*unchecked((int)DateTime.Now.Ticks));
}
//int t = rand.Next(35) ;
int t=rand.Next(35);
if (temp != -1 && temp == t)
{
return RndNum( VcodeNum );
}
temp = t ;
VNum += VcArray[t];
}
return VNum ;
}
-----------------------------------end--------------------------------------------
下面是Login.Aspx在在調用提交按鈕的響應事件中
public void doit(object sender, System.EventArgs e)
{
if(Page.IsValid)
{
string VNum;
VNum=Session["VNum"].ToString();
Session.Abandon();
ViewState["VNum"]=VNum;
if(this.Vcode.Text==ViewState["VNum"].ToString())
{
Hover.Manage.CheckLogin obj=new Hover.Manage.CheckLogin();
string name=username.Text;
string password=FormsAuthentication.HashPasswordForStoringInConfigFile(pass.Text.ToString(),"md5");
if(!obj.checklogin(name,password))
{
Response.Redirect("../Error.aspx?action=Errorlogin");
Response.End();
return;
}
else
{
Session.Add("adminname",name);
Session.Add("adminpass",password);
Response.Redirect("Default.aspx");
Response.End();
return;
}
}
else
{
Response.Write("<script>alert(\"請輸入正確的附加碼!\");</script>");
}
}
}
如果提交過來的驗證字串正確就驗證是否是合法使用者!
否則彈出提示返回登陸頁!你也可以簡化此頁!
if(this.Vcode.Text==ViewState["VNum"].ToString())
{
Response.Write("驗證碼正確");
}
else
{
Response.Write("驗證碼錯誤!");
}