一、核心应用场景
- 用户登录/注册验证:防止恶意程序批量注册
- 表单提交防护:确保关键操作由真人执行
- API接口限流:抵御自动化脚本攻击
- 敏感操作验证:如支付、信息修改等关键步骤
- 数据防爬机制:保护网站内容不被爬虫抓取
二、技术实现方案
1. 基础架构设计
// 验证码服务架构 +------------------------+ | 验证码生成模块 | ← 随机字符 | (CaptchaGenerator) | +------------------------+ ↓ +------------------------+ | 图像处理模块 | ← 添加干扰元素 | (ImageProcessor) | +------------------------+ ↓ +------------------------+ | 验证码存储模块 | → Redis/Session | (CaptchaStorage) | +------------------------+
2. 完整实现代码(ASP.NET MVC)
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web.Mvc;
namespace CaptchaDemo.Controllers
{
public class CaptchaController : Controller
{
/// <summary>
/// 生成验证码图片(带干扰元素)
/// </summary>
[HttpGet]
public ActionResult Generate(int width = 120, int height = 40)
{
// 生成随机验证码(4-6位)
string captchaCode = GenerateRandomCode(4);
// 创建位图对象
using (Bitmap bitmap = new Bitmap(width, height))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
// 设置画布属性
g.Clear(Color.WhiteSmoke);
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
// 添加干扰线(5-8条)
AddNoiseLines(g, width, height);
// 绘制验证码文字
DrawCaptchaText(g, captchaCode, width, height);
// 添加噪点(100-200个)
AddNoisePoints(bitmap, width, height);
}
// 输出图片流
using (MemoryStream stream = new MemoryStream())
{
bitmap.Save(stream, ImageFormat.Jpeg);
return File(stream.ToArray(), "image/jpeg");
}
}
}
/// <summary>
/// 生成随机验证码(包含数字和字母)
/// </summary>
private string GenerateRandomCode(int length)
{
const string chars = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"; // 排除易混淆字符
Random random = new Random(Guid.NewGuid().GetHashCode());
char[] result = new char[length];
for (int i = 0; i < length; i++)
{
result[i] = chars[random.Next(chars.Length)];
}
return new string(result);
}
/// <summary>
/// 绘制干扰线
/// </summary>
private void AddNoiseLines(Graphics g, int width, int height)
{
Random random = new Random();
for (int i = 0; i < 6; i++)
{
int x1 = random.Next(width);
int y1 = random.Next(height);
int x2 = random.Next(width);
int y2 = random.Next(height);
g.DrawLine(new Pen(Color.FromArgb(
random.Next(128, 256),
random.Next(128, 256),
random.Next(128, 256))), x1, y1, x2, y2);
}
}
/// <summary>
/// 绘制验证码文字(带旋转效果)
/// </summary>
private void DrawCaptchaText(Graphics g, string code, int width, int height)
{
Random random = new Random();
float charWidth = width / (code.Length + 1);
for (int i = 0; i < code.Length; i++)
{
// 设置随机颜色
Brush brush = new SolidBrush(Color.FromArgb(
random.Next(50, 150),
random.Next(50, 150),
random.Next(50, 150)));
// 随机旋转角度(-30°到30°)
g.TranslateTransform(
charWidth * i + charWidth / 2,
height / 2);
g.RotateTransform(random.Next(-30, 30));
// 绘制文字
g.DrawString(
code[i].ToString(),
new Font("Arial", 18, FontStyle.Bold),
brush,
new PointF(-charWidth / 3, -10),
StringFormat.GenericTypographic);
// 重置变换矩阵
g.ResetTransform();
}
}
/// <summary>
/// 添加噪点
/// </summary>
private void AddNoisePoints(Bitmap bitmap, int width, int height)
{
Random random = new Random();
for (int i = 0; i < 150; i++)
{
int x = random.Next(width);
int y = random.Next(height);
bitmap.SetPixel(x, y, Color.FromArgb(
random.Next(256),
random.Next(256),
random.Next(256)));
}
}
}
}
三、前端集成教程
1. HTML视图代码
<div class="captcha-box">
<img id="captchaImg" src="@Url.Action("Generate", "Captcha")"
onclick="refreshCaptcha()"
title="点击刷新验证码"/>
<input type="text" id="captchaInput" placeholder="输入验证码"/>
</div>
2. JavaScript交互
function refreshCaptcha() {
// 添加时间戳防止缓存
let timestamp = new Date().getTime();
document.getElementById('captchaImg').src =
'@Url.Action("Generate", "Captcha")?t=' + timestamp;
}
// 表单提交验证示例
function validateCaptcha() {
let userInput = document.getElementById('captchaInput').value;
fetch('/Captcha/Validate?code=' + userInput)
.then(response => {
if(!response.ok) throw new Error('验证码错误');
// 后续提交逻辑...
});
}
四、服务端验证实现
/// <summary>
/// 验证码校验(需配合Session或Redis存储)
/// </summary>
[HttpPost]
public ActionResult Validate(string code)
{
string sessionCode = Session["CaptchaCode"]?.ToString();
if(string.IsNullOrEmpty(sessionCode))
return Json(new { success = false, message = "验证码已过期" });
bool isValid = code.Equals(sessionCode,
StringComparison.OrdinalIgnoreCase);
// 验证后清除Session
Session.Remove("CaptchaCode");
return Json(new { success = isValid });
}
(注:实际部署时需要根据大家的实际情况添加异常处理和日志记录模块)