您的位置:首页 > 编程语言 > ASP

里如何生成验证码asp.net

2006-01-22 14:10 399 查看
今天上网搜了搜怎么来生成验证码,例子好多的,看了一篇文章,有了一个大概的了解

我对 .net 的类 如BitMap 还不太了解,只能根据别人的来做了。他是用 VB .net 来做的,俺不会 VB.net ,只能用 C# 了。

首先新建一个 Web 项目,完成后新建一个Web 窗体,名为 Gif.aspx

建一方法

private void createPic(string str)
{
System.Drawing.Bitmap bmp;
System.Drawing.Graphics g;
System.IO.MemoryStream ms;

// 还不明白为什么要这样做,一会再看看教程

int picLen=str.Length*12;

bmp=new Bitmap(picLen,20);
g=System.Drawing.Graphics.FromImage(bmp);
g.DrawString(str,(new Font("Arial",12)),(new SolidBrush(Color.Blue)),1,1);

ms=new System.IO.MemoryStream();
bmp.Save(ms,ImageFormat.Png);
Response.ClearContent();
Response.ContentType="image/png";
Response.BinaryWrite(ms.ToArray());

g.Dispose();
bmp.Dispose();
Response.End();

}

做一个生成随机数的方法

private string createRandomiz(int n)
{
System.Random r=new Random();
string str="0,1,2,3,4,5,6,7,8,9,q,w,e,r,t,y,u,i,o,p,a,s,d,f,g,h,j,k,l,z,x,c,v,b,n,m";
char[] a=new char[1];
a[0]=',';

string[] str1=str.Split(a);
string temp="";
for ( int i=0 ;i<n;i++)
{

temp=temp+str1[r.Next(35)].ToString();

}
return temp;
}

然后在 page_load 里调用就行了
private void Page_Load(object sender, System.EventArgs e)
{
string num=this.createRandomiz(4); // 生成 4 个随机数
Session["a"]=num; //这里用 Session 来保存
this.createPic(num);
}

在 WebForm1 里加一个 image 的 web 服务器控件 将 imageUrl 设为 gif.aspx
拖放一个 button 和一个 TextBox
在 Button 里写

if ( this.TextBox1.Text !=Session["a"].ToString())
{
Response.Write("error");
}
else
{
Response.Write("ok");
}

这样就完成了,继续看教程了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: