为了便于大家学习,修改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="所填写的验证码与所给的不符";
}
}