在做一个登录页时,我们通常需要设置验证码,防止非法人员通过其他手段非法登录。在做一个页面的验证码时,我们需要先建立一个Active的Web页面,来随机的产生数字和字母,同时把产生的数字存储在Session中,传递给登录页,用来验证。并且定义一个画板,在Active页面绘出验证码的背景颜色,在Active页面的代码如下:
protected void Page_Load(object sender, EventArgs e)
{
//显示验证码
this.GenImg(this.GenCode(4));
Session["image"] = this.GenCode(4);
Server.Transfer("Default.aspx");
//Console.WriteLine(this.GenCode(4));
}
private string GenCode(int num)
{
string [] source={"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","V","W","X","Y","Z"};
string code = "";
//创建Random类的实例
Random rd = new Random();
//获取验证码
for (int i = 0; i < num; i++)
{
code += source[rd.Next(0, source.Length)];
}
//返回产生的验证码
return code;
}
//生成图片
private void GenImg(string code)
{
//定义一个画板
Bitmap myPalette = new Bitmap(60, 20);
//在画板上定义绘图的实例
Graphics gh = Graphics.FromImage(myPalette);
//定义一个矩形
Rectangle rc = new Rectangle(0, 0, 60, 20);
//填充矩形
gh.FillRectangle(new SolidBrush(Color.Blue), rc);
//在矩形内画出字符串
gh.DrawString(code, new Font("宋体", 16), new SolidBrush(Color.White), rc);
//将图片显示出来
myPalette.Save(Response.OutputStream, ImageFormat.Jpeg);
gh.Dispose();
myPalette.Dispose();
}
当我们完成了,在Active页面动态的随机产生验证码以后,我们要在登录页接收,随机产生的验证码,并显示出来,代码如下:
protected void Page_Load(object sender, EventArgs e)
{
//设置btnimage控件的ImageUrl属性为验证码的页面
this.ImageButton1.ImageUrl = "Active.aspx";
}
protected void Button1_Click(object sender, EventArgs e)
{
string Code =Session["image"].ToString().Trim();
//Console.WriteLine(Code);
string Txtbox = this.TextBox3.Text.ToString().Trim();
if (Code==Txtbox.ToUpper())
{
Response.Redirect("Result.aspx");
}
else
Response.Write("<script language='javascript'>alert('跳转失败!');</script>");
}
到此,就完成了一个动态产生验证码的全过程,并且完成验证的代码。
版权声明:本文为博主原创文章,未经博主允许不得转载。