服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服务器之家 - 编程语言 - ASP.NET教程 - asp.net验证码的简单制作

asp.net验证码的简单制作

2019-12-21 14:17lijiao ASP.NET教程

当用户进行注册、登陆的时候都会遇到输入验证码的情况,那验证码到底是怎么制作的,下面就为大家讲解如何使用ASP.NET制作简单的验证码,感兴趣的朋友可以参考一下

实际上关于asp.net验证码制作的文章已经很多很多了,但是今天还是要和大家继续分享,亲,可以综合几篇实例,编写出适用于自己网站的ASP.NET验证码,大概也就两大部分:

先建立一个asp.net窗体ValidateCode.aspx;不写任何东西。直接在后台ValidateCode.aspx.cs中写如下代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
protected void Page_Load(object sender, EventArgs e)
{     
  string validateCode = CreateValidateCode();//生成验证码
  Bitmap bitmap = new Bitmap(imgWidth,imgHeight);//生成Bitmap图像
  DisturbBitmap(bitmap); //图像背景
  DrewValidateCode(bitmap,validateCode);//绘制验证码图像
  bitmap.Save(Response.OutputStream,ImageFormat.Gif);//保存图像,等待输出
 
}
 
private int codeLen = 4;//验证码长度
private int fineness = 85;//图片清晰度
private int imgWidth = 48;//图片宽度
private int imgHeight = 24;//图片高度
private string fontFamily = "Times New Roman";//字体名称
private int fontSize = 14;//字体大小
//private int fontStyle = 0;//字体样式
private int posX = 0;//绘制起始坐标X
private int posY = 0;//绘制坐标Y
private string CreateValidateCode() //生成验证码
{
  string validateCode = "";
  Random random = new Random();// 随机数对象
  for (int i = 0; i < codeLen; i++)//循环生成每位数值
  {
    int n = random.Next(10);//数字
    validateCode += n.ToString();
  }
  Session["vcode"] = validateCode;//保存验证码 这Session是在前台调用的。
  return validateCode;// 返回验证码
}
 
private void DisturbBitmap(Bitmap bitmap)//图像背景
{
  Random random = new Random();//通过随机数生成
  for (int i = 0; i < bitmap.Width; i++)//通过循环嵌套,逐个像素点生成
  {
    for (int j = 0; j < bitmap.Height; j++)
    {
      if (random.Next(90) <= this.fineness)
        bitmap.SetPixel(i, j, Color.LightGray);
    }
  }
}
private void DrewValidateCode(Bitmap bitmap, string validateCode)//绘制验证码图像
{
  Graphics g = Graphics.FromImage(bitmap);//获取绘制器对象
  Font font = new Font(fontFamily, fontSize, FontStyle.Bold);//设置绘制字体
  g.DrawString(validateCode, font, Brushes.Black, posX, posY);//绘制验证码图像
}

在Login.aspx窗体页面中实现如下图功能:

asp.net,验证码

Login.aspx窗体前台:

?
1
2
3
4
5
6
7
8
9
10
//这个函数是在点击验证码图片就会更换验证码
//可以使用微软自带的jqury.js 下面jquery-1.4.1.min.js版本之上的。或者在jquery官网上下载就可以。
 <script src="styles/jquery-1.4.1.min.js" type="text/javascript"></script>
     function f_refreshtype() {
       var Image1 = document.getElementByIdx_x_x_x("img");
       if (Image1 != null) {
         Image1.src = Image1.src + "?";
       }
     }
---<img src="ValidateCode.aspx" id="img" onclick="f_refreshtype()" width="50px"/>//调用函数,实现更换验证码

后台代码:点击登录验证用户是否输入正确。 

?
1
2
3
4
string usercode = txtcode.Text.Trim();
    if (usercode == Session["vcode"].ToString())//Session["vcode"]
    {
}

其他代码就是跟其他一样。

以上就是跟大家分享的关于生成ASP.NET验证码的过程,希望大家可以学以致用。

延伸 · 阅读

精彩推荐