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

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - ASP.NET教程 - ASP.NET实现的生成验证码功能示例【附demo源码】

ASP.NET实现的生成验证码功能示例【附demo源码】

2020-05-12 15:02Terry Chen ASP.NET教程

这篇文章主要介绍了ASP.NET实现的生成验证码功能,结合实例形式较为详细的分析了asp.net生成验证码的原理、步骤与相关实现技巧,并附带demo源码供读者下载参考,需要的朋友可以参考下

本文实例讲述了ASP.NET实现的生成验证码功能。分享给大家供大家参考,具体如下:

生成验证码原理:产生随机字符,并将字符生成为图片,同时储存到Session里去,然后验证用户输入的内容是否与Session中的验证码相符即可。

效果图:用户可以点击切换验证码信息。

ASP.NET实现的生成验证码功能示例【附demo源码】

一般处理程序:CheckCodeHandler.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<%@ WebHandler Language="C#" Class="CheckCodeHandler" %>
using System;
using System.Web;
using System.Text;
using System.Drawing;
using System.Web.SessionState;
public class CheckCodeHandler : IHttpHandler,IRequiresSessionState
{
  //产生验证码的字符集
  public string charcode = "2,3,4,5,6,8,9,A,B,C,D,E,F,G,H,J,K,M,N,P,R,S,U,W,X,Y,a,b,c,d,e,f,g,h,j,k,m,n,p,r,s,u,w,x,y";
  public void ProcessRequest (HttpContext context) {
    string validateCode = CreateRandomCode(4);
    context.Session["ValidateCode"] = validateCode;//将验证码保存到session中
    CreateCodeImage(validateCode, context);
  }
  public bool IsReusable {
    get {
      return false;
    }
  }
  /// <summary>
  /// 生成验证码
  /// </summary>
  /// <param name="n">验证码个数</param>
  /// <returns>验证码字符串</returns>
  public string CreateRandomCode(int n)
  {
    string[] CharArray = charcode.Split(',');//将字符串转换为字符数组
    string randomCode = "";
    int temp = -1;
    Random rand = new Random();
    for (int i = 0; i < n; i++)
    {
      if (temp != -1)
      {
        rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
      }
      int t = rand.Next(CharArray.Length - 1);
      if (temp != -1 && temp == t)
      {
        return CreateRandomCode(n);
      }
      temp = t;
      randomCode += CharArray[t];
    }
    return randomCode;
  }
  public void CreateCodeImage(string checkCode, HttpContext context)
  {
    int iwidth = (int)(checkCode.Length * 13);
    System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 20);
    Graphics g = Graphics.FromImage(image);
    Font f = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Italic | System.Drawing.FontStyle.Bold));
    // 前景色
    Brush b = new System.Drawing.SolidBrush(Color.Black);
    // 背景色
    g.Clear(Color.White);
    // 填充文字
    g.DrawString(checkCode, f, b, 0, 1);
    // 随机线条
    Pen linePen = new Pen(Color.Gray, 0);
    Random rand = new Random();
    for (int i = 0; i < 5; i++)
    {
      int x1 = rand.Next(image.Width);
      int y1 = rand.Next(image.Height);
      int x2 = rand.Next(image.Width);
      int y2 = rand.Next(image.Height);
      g.DrawLine(linePen, x1, y1, x2, y2);
    }
    // 随机点
    for (int i = 0; i < 30; i++)
    {
      int x = rand.Next(image.Width);
      int y = rand.Next(image.Height);
      image.SetPixel(x, y, Color.Gray);
    }
    // 边框
    g.DrawRectangle(new Pen(Color.Gray), 0, 0, image.Width - 1, image.Height - 1);
    // 输出图片
    System.IO.MemoryStream ms = new System.IO.MemoryStream();
    image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
    context.Response.ClearContent();
    context.Response.ContentType = "image/jpeg";
    context.Response.BinaryWrite(ms.ToArray());
    g.Dispose();
    image.Dispose();
  }
}

封装成类库:ValidateNumber.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using System.Web.UI;
using System.Drawing.Drawing2D;
using System.IO;
using System.Drawing.Imaging;
/// <summary>
///ValidateNumber 生成验证码
/// </summary>
public class ValidateNumber
{
  //产生验证码的字符集 (易混淆的字符去掉)
  private string charcode = "2,3,4,5,6,8,9,A,B,C,D,E,F,G,H,J,K,M,N,P,R,S,U,W,X,Y,a,b,c,d,e,f,g,h,j,k,m,n,p,r,s,u,w,x,y";
  /// <summary>
  /// 验证码的最大长度
  /// </summary>
  public int MaxLength
  {
    get { return 10; }
  }
  /// <summary>
  /// 验证码的最小长度
  /// </summary>
  public int MinLength
  {
    get { return 1; }
  }
  /// <summary>
  /// 生成验证码
  /// </summary>
  /// <param name="length">指定验证码的长度</param>
  /// <returns></returns>
  public string CreateValidateNumber(int length)
  {
    string[] CharArray = charcode.Split(',');//将字符串转换为字符数组
    string randomCode = "";
    int temp = -1;
    Random rand = new Random();
    for (int i = 0; i < length; i++)
    {
      if (temp != -1)
      {
        rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
      }
      int t = rand.Next(CharArray.Length - 1);
      if (temp != -1 && temp == t)
      {
        return CreateValidateNumber(length);
      }
      temp = t;
      randomCode += CharArray[t];
    }
    return randomCode;
  }
  /// <summary>
  /// 创建验证码的图片
  /// </summary>
  /// <param name="context">context对象</param>
  /// <param name="validateNum">验证码</param>
  public void CreateValidateGraphic(HttpContext context,string validateNum)
  {
    int iwidth = (int)(validateNum.Length * 14);
    Bitmap image = new Bitmap(iwidth, 22);
    Graphics g = Graphics.FromImage(image);
    try
    {
      //生成随机生成器
      Random random = new Random();
      //清空图片背景色
      g.Clear(Color.White);
      //画图片的干扰线
      for (int i = 0; i < 25; i++)
      {
        int x1 = random.Next(image.Width);
        int x2 = random.Next(image.Width);
        int y1 = random.Next(image.Height);
        int y2 = random.Next(image.Height);
        g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
      }
      Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));
      LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),
       Color.Blue, Color.DarkRed, 1.2f, true);
      g.DrawString(validateNum, font, brush, 3, 2);
      //画图片的前景干扰点
      for (int i = 0; i < 100; i++)
      {
        int x = random.Next(image.Width);
        int y = random.Next(image.Height);
        image.SetPixel(x, y, Color.FromArgb(random.Next()));
      }
      //画图片的边框线
      g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
      //保存图片数据
      MemoryStream stream = new MemoryStream();
      image.Save(stream, ImageFormat.Jpeg);
      //输出图片
      context.Response.Clear();
      context.Response.ContentType = "image/jpeg";
      context.Response.BinaryWrite(stream.ToArray());
    }
    finally
    {
      g.Dispose();
      image.Dispose();
    }
  }
  /// <summary>
  /// 得到验证码图片的长度
  /// </summary>
  /// <param name="validateNumLength">验证码的长度</param>
  /// <returns></returns>
  public static int GetImageWidth(int validateNumLength)
  {
    return (int)(validateNumLength * 14);
  }
  /// <summary>
  /// 得到验证码图片的高度
  /// </summary>
  /// <returns></returns>
  public static double GetImageHeight()
  {
    return 22;
  }
}

附:完整实例代码点击此处本站下载

希望本文所述对大家asp.net程序设计有所帮助。

延伸 · 阅读

精彩推荐