日期:2012-03-01 浏览次数:20556 次
第一.两个页面Login.aspx和gif.aspx。
第二.Login.aspx页面的image控件的URL指定为gif.aspx。
第三.gif.aspx页面代码如下:
private void Page_Load(object sender, System.EventArgs e)
{
string strNum = RandNum(4);
Session["Test"] = strNum;
ValidateCode(strNum);
ViewState["Test"] = strNum;
}
/// <summary>
/// 产生随机数
/// </summary>
/// <param name="iNum">种子</param>
/// <returns></returns>
/// <author>tianzm</author>
/// <history>2005-06-18</history>
private string RandNum(int iNum)
{
string strChar = "0,1,2,3,4,5,6,7,8,9,0,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
string[] strAry = strChar.Split(',');
string strNum = "";
System.Random obj = new Random();
for ( int i=0; i<iNum; i++)
{
int index = obj.Next(strAry.Length);
strNum = strNum + strAry[index];
}
return strNum;
//这里可以对产生的随机数,进行加密处理。
}
/// <summary>
/// 重画图像生成
/// </summary>
/// <param name="strNum">验证码</param>
/// <author>tianzm</author>
/// <history>2005-06-18</history>
private void ValidateCode(string strNum)
{
System.Drawing.Bitmap img = null;
System.Drawing.Graphics g = null;
System.IO.MemoryStream ms = null;
int iWidth = Convert.ToInt16(strNum.Length * 11.5);
img = new Bitmap(iWidth,20);
g = Graphics.FromImage(img);
g.DrawString(strNum,(new Font("Arial",10)),(new SolidBrush(Color.Blue)),3,3);
ms = new MemoryStream();
img.Save(ms,ImageFormat.Png);
Response.ClearContent();
Response.ContentType = "image/Png";
Response.BinaryWrite(ms.ToArray());
g.Dispose();
img.Dispose();
Response.End();
}
在Login.aspx页面验证如下:
string strTemp = Session["Test"].ToString();
Session.Abandon();
ViewState["TestNum"] = strTemp;
if ( this.TextBox1.Text == ViewState["TestNum"].ToString() )
{
this.Label1.Text = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
}