ASP.NET实现图片式验证码并能点击刷新

wangweikui_code
最近用.NET做一个网站注册页面用到验证码功能,就想着用C#实现一下,同时也有参考网上众多实例,浏览一番下来发现方法也都大同小异,关键是有个重要问题好像都没解决,就是验证码字符串的读取问题,虽然都是用session获取,但输入框中获取到的字符串值都是上一次验证码生成时候的session值,明显有误。最终经过修改后终于调试成功一个完整的实现验证码的功能,而且参数方便更改。

首先新建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
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
//验证码类型(0-字母数字混合,1-数字,2-字母)    
private string validateCodeType = "0";
// 验证码字符个数
private int validateCodeCount = 4;
// 验证码的字符集,去掉了一些容易混淆的字符
char[] character = { '2', '3', '4', '5', '6', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p', 'r', 's', 't', 'w', 'x', 'y' };
protected void Page_Load(object sender, EventArgs e)
{
//取消缓存
Response.BufferOutput = true;
Response.Cache.SetExpires(DateTime.Now.AddMilliseconds(-1));
Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
Response.AppendHeader("Pragma", "No-Cache");
//获取设置参数
if (!string.IsNullOrEmpty(Request.QueryString["validateCodeType"]))
{
validateCodeType = Request.QueryString["validateCodeType"];
}
if (!string.IsNullOrEmpty(Request.QueryString["validateCodeCount"]))
{
int.TryParse(Request.QueryString["validateCodeCount"], out validateCodeCount);
}
//生成验证码
this.CreateCheckCodeImage(GenerateCheckCode());
}
private string GenerateCheckCode()
{
char code;
string checkCode = String.Empty;
System.Random random = new Random();
for (int i = 0; i < validateCodeCount; i++)
{
code = character[random.Next(character.Length)];
// 要求全为数字或字母
if (validateCodeType == "1")
{
if ((int)code < 48 || (int)code > 57)
{
i--;
continue;
}
}
else if (validateCodeType == "2")
{
if ((int)code < 65 || (int)code > 90)
{
i--;
continue;
}
}
checkCode += code;
}
Response.Cookies.Add(new System.Web.HttpCookie("CheckCode", checkCode));
this.Session["CheckCode"] = checkCode;
return checkCode;
}
private void CreateCheckCodeImage(string checkCode)
{
if (checkCode == null || checkCode.Trim() == String.Empty)
return;
//设置验证码图片的长宽值
System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 15.0 + 30)), 40);
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);
try
{
//生成随机生成器
Random random = new Random();
//清空图片背景色
g.Clear(System.Drawing.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 System.Drawing.Pen(System.Drawing.Color.Silver), x1, y1, x2, y2);
}
System.Drawing.Font font = new System.Drawing.Font("Arial", 16, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new System.Drawing.Rectangle(0, 0, image.Width, image.Height), System.Drawing.Color.Blue, System.Drawing.Color.DarkRed, 1.2f, true);
int cySpace = 15; //控制字符间距
for (int i = 0; i < validateCodeCount; i++)
{
g.DrawString(checkCode.Substring(i, 1), font, brush, (i + 1) * cySpace, 1);
}
//画图片的前景噪音点
for (int i = 0; i < 100; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);
image.SetPixel(x, y, System.Drawing.Color.FromArgb(random.Next()));
}
//画图片的边框线
g.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
Response.ClearContent();
Response.ContentType = "image/Gif";
Response.BinaryWrite(ms.ToArray());
}
finally
{
g.Dispose();
image.Dispose();
}
}

新建ValidateTest.aspx 用于显示验证码

前台重要的是image标签,配合input和button完成简单的验证码验证功能。前台代码如下:

1
2
3
4
5
6
7
8
<form id="form1" runat="server">
<div>
<input runat="server" id="txtValidate" />
<img src="ValidateCode.aspx?validateCodeCount=5" onclick="this.src='ValidateCode.aspx?validateCodeCount=5&'+Math.random();"
id="imgValidateCode" alt="点击刷新验证码" title="点击刷新验证码" style="cursor: pointer;" />
<asp:Button runat="server" ID="btnVal" Text="提交" OnClick="btnVal_Click" />
</div>
</form>

后台ValidateTest.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
protected void btnVal_Click(object sender, EventArgs e)
{
bool result = false; //验证结果
string userCode = this.txtValidate.Value; //获取用户输入的验证码
if (String.IsNullOrEmpty(userCode))
{
//请输入验证码
return;
}
string validCode = this.Session["CheckCode"] as String; //获取系统生成的验证码
if (!string.IsNullOrEmpty(validCode))
{
if (userCode.ToLower() == validCode.ToLower())
{
//验证成功
result = true;
Response.Write("<script>alert(\"验证码输入正确!\")</script>");
}
else
{
//验证失败
result = false;
Response.Write("<script>alert(\"验证码输入错误!\")</script>");
}
}
}

程序演示效果如下:

wangweikui_validate1
wangweikui_validate2
从代码注释可以注意到,该验证码程序能够方便的设置验证码内容是数字或是大小字母或者混合组合,以及验证码字符位数,图片样式等内容,还是能够方便的嵌入到自己的网站的任何位置。接下来就可以愉快的进入项目的下一个阶段了。