第一.两个页面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";
}
新闻热点
疑难解答