网站海外推广服务,机械电子工程网,西宁做网站哪家好,石家庄白帽seo网络公司ASP.NET 实现图形验证码能够增强网站安全性#xff0c;防止机器人攻击。通过生成随机验证码并将其绘制成图像#xff0c;用户在输入验证码时增加了人机交互的难度。本文介绍了如何使用 C# 和 ASP.NET 创建一个简单而有效的图形验证码系统#xff0c;包括生成随机验证码、绘制…ASP.NET 实现图形验证码能够增强网站安全性防止机器人攻击。通过生成随机验证码并将其绘制成图像用户在输入验证码时增加了人机交互的难度。本文介绍了如何使用 C# 和 ASP.NET 创建一个简单而有效的图形验证码系统包括生成随机验证码、绘制验证码图像以及将图像输出到客户端等步骤。这种验证码系统对于保护网站免受恶意攻击和机器人恶意行为具有重要意义。 一、实现思路
我们需要实现一个防爬虫的可以动态刷新的随机验证码图片。 比如下面这种 关键点
动态每次打开页面验证码是变化的并且验证码在一些事件下会自发刷新成新的验证码比如在点击、输入错误、页面停靠超时等事件触发时验证码自动刷新。随机里面的数字和字母是随机的是一种强密码不容易被暴力破解。防爬防止爬虫通过一些AI识别直接通过我们需要增加图片的复杂度例如添加一些干扰性的图案包括但不限于噪音线、噪点等。
验证码生成成功后我们还需要将验证码保存到 Session 中以便后续验证。 二、编写前端代码
思路已经明确下面我们来构建图形验证码的前端代码。 前端代码包含 HTML 和 JavaScript 代码。
1、编写HTML代码
HTML代码包含一个简单的验证码输入框和刷新图片按钮的用户界面
div classcheckcodeinput typetext runatserver idVercodeText placeholder验证码 maxlength4img onclickchangepic(this) src/handlers/VerCode.ashx /
/div
div classcheckcode创建一个包含验证码元素的 div 容器用于样式控制。input typetext runatserver idVercodeText placeholder验证码 maxlength4添加一个文本输入框用于用户输入验证码。设置了ID为 VercodeText最大长度为4同时提供了占位符 验证码。img οnclickchangepic(this) src/handlers/VerCode.ashx /插入一个图片元素其 src 属性指向验证码处理器 VerCode.ashx。当用户点击该图片时触发JavaScript函数 changepic 进行验证码图像的刷新。
通过这样的HTML结构用户可以在输入框中输入验证码并通过点击图片刷新验证码图像提供了一种交互式的验证码体验。 2、创建JavaScript函数
创建 changepic 函数方法
function changepic(obj) {var timestamp (new Date().getTime()) / 1000;$(obj).attr(src, VerCode.ashx?tims timestamp);
}
changepic 函数用于刷新验证码图片通过在 URL 中添加时间戳的方式确保每次请求都是唯一的避免浏览器缓存。 三、编写后端代码
后端代码我们采用C#实现。
1、创建输出图形验证码的接口
创建C#验证码处理器 VerCode.ashx
using CarRental.Common;
using System;
using System.Drawing;
using System.IO;
using System.Web;namespace Handlers
{public class VerCode : IHttpHandler, System.Web.SessionState.IRequiresSessionState{public void ProcessRequest(HttpContext context){}public bool IsReusable{get{return false;}}}
}VerCode 类实现了 IHttpHandler 接口用于处理 HTTP 请求。 2、创建验证码生成方法
/// summary
/// 随机构建验证码方法
/// /summary
/// returns返回验证码字符串/returns
public string CreateCode()
{char code;string checkCode string.Empty;Random rd new Random();for (int i 0; i 4; i){int num rd.Next();int _temp;if (num % 2 0){_temp (0 (char)(num % 10));if (_temp 48 || _temp 49){_temp rd.Next(2, 9);}}else{_temp (A (char)(num % 10));if (rd.Next(0, 2) 0){_temp (char)(_temp 32);}if (_temp 66 || _temp 73 || _temp 79 || _temp 108 || _temp 111){_temp;}}code (char)_temp;checkCode code;}return checkCode;
}CreateCode 方法用于生成随机验证码包含数字和字母并进行了一些特殊字符的处理以增加验证码的复杂性。 3、 绘制验证码图片
① 配置验证码参数
我们先定义验证码图像的宽度、高度、字体大小以及用于生成随机数的 Random 对象。
int codeWeight 80;
int codeHeight 22;
int fontSize 16;
Random rd new Random(); ② 生成验证码字符串
这一步很简单我们直接调用之前写好的 CreateCode 方法。
string checkCode CreateCode(); ③ 构建验证码背景
创建一个位图对象并在其上创建图形对象然后用白色填充图像背景。
Bitmap image new Bitmap(codeWeight, codeHeight);
Graphics g Graphics.FromImage(image);
g.Clear(Color.White); ④ 画噪音线
在图像上绘制两条随机颜色的噪音线增加验证码的复杂性。
for (int i 0; i 2; i)
{int x1 rd.Next(image.Width);int x2 rd.Next(image.Width);int y1 rd.Next(image.Height);int y2 rd.Next(image.Height);g.DrawLine(new Pen(color[rd.Next(color.Length)]), new Point(x1, y1), new Point(x2, y2));
} ⑤ 画验证码
使用循环逐个绘制验证码字符串中的字符每个字符使用随机颜色和字体。
for (int i 0; i checkCode.Length; i)
{Color clr color[rd.Next(color.Length)];Font ft new Font(font[rd.Next(font.Length)], fontSize);g.DrawString(checkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 18 2, 0);
}⑥ 画噪音点
在图像上绘制100个随机颜色的噪音点增加验证码的随机性。
for (int i 0; i 100; i)
{int x rd.Next(image.Width);int y rd.Next(image.Height);image.SetPixel(x, y, Color.FromArgb(rd.Next()));
} ⑦ 画边框线
在图像周围绘制银色边框线使验证码更加清晰。
g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);⑧ 将验证码图像保存到内存流
将生成的验证码图像保存到内存流中准备输出到客户端。
MemoryStream ms new MemoryStream(); image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); ⑨ 将验证码保存到Session中
将生成的验证码字符串保存到Session中以便后续验证。
context.Session[ConstantValues.VerCodeSessionName] checkCode; ⑩ 输出图像到客户端
配置HTTP响应将验证码图像输出到客户端。
context.Response.ContentType Image/Gif;
context.Response.ClearContent();
context.Response.BinaryWrite(ms.ToArray());
最后别忘记释放图像和图形资源防止内存泄漏。
finally { image.Dispose(); g.Dispose(); } 4、完整后端代码
完整的 VerCode.cs 代码如下
using TestMoudle.Common;
using System;
using System.Drawing;
using System.IO;
using System.Web;namespace Handlers
{public class VerCode : IHttpHandler, System.Web.SessionState.IRequiresSessionState{public void ProcessRequest(HttpContext context){int codeWeight 80;int codeHeight 22;int fontSize 16;Random rd new Random();string checkCode CreateCode(); //构建验证码字符串Bitmap image new Bitmap(codeWeight, codeHeight); //构建画图Graphics g Graphics.FromImage(image); //构建画布g.Clear(Color.White); //清空背景色Color[] color new Color[] { Color.Red, Color.Black, Color.Green, Color.Blue };string[] font new string[] { 宋体, 黑体, 楷体 };//画噪音线for (int i 0; i 2; i){int x1 rd.Next(image.Width);int x2 rd.Next(image.Width);int y1 rd.Next(image.Height);int y2 rd.Next(image.Height);g.DrawLine(new Pen(color[rd.Next(color.Length)]), new Point(x1, y1), new Point(x2, y2));}//画验证码for (int i 0; i checkCode.Length; i){Color clr color[rd.Next(color.Length)];Font ft new Font(font[rd.Next(font.Length)], fontSize);g.DrawString(checkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 18 2, 0);}//画噪音点for (int i 0; i 100; i){int x rd.Next(image.Width);int y rd.Next(image.Height);image.SetPixel(x, y, Color.FromArgb(rd.Next()));}//画边框线g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);MemoryStream ms new MemoryStream();try{image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);context.Session[ConstantValues.VerCodeSessionName] checkCode; //将验证码保存到Session中context.Response.ContentType Image/Gif;context.Response.ClearContent();context.Response.BinaryWrite(ms.ToArray());}finally{image.Dispose();g.Dispose();}}public bool IsReusable{get{return false;}}}
}四、测试效果
我们运行项目可以看到验证码图像顺利生成了并且点击可以刷新图片内容。