在ASP.NET开发中,验证码是防范恶意表单提交、接口暴力请求的基础功能,实现简单实用的验证码不需要复杂的逻辑,核心分为生成验证码图片、存储验证码值、前端展示、后端校验四个步骤。

实现思路说明
首先我们需要生成随机的验证码字符串,然后将字符串绘制成图片返回给前端,同时将验证码字符串存入Session中,用户提交表单时对比输入的验证码和Session中存储的值即可完成校验。
1. 生成随机验证码字符串
我们可以定义一个方法生成指定长度的随机字符串,包含数字和大小写字母,提升验证码的识别难度。
using System;
public class VerifyCodeHelper
{
/// <summary>
/// 生成随机验证码字符串
/// </summary>
/// <param name="length">验证码长度</param>
/// <returns>随机字符串</returns>
public static string GenerateCode(int length)
{
string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
Random random = new Random();
char[] codeArray = new char[length];
for (int i = 0; i < length; i++)
{
codeArray[i] = chars[random.Next(chars.Length)];
}
return new string(codeArray);
}
}
2. 生成验证码图片的HttpHandler
ASP.NET中可以通过实现IHttpHandler接口来生成动态图片,我们将验证码字符串绘制到图片上,然后输出为JPEG格式返回给前端。
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web;
using System.Web.SessionState;
public class VerifyCodeHandler : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
// 生成4位验证码
string code = VerifyCodeHelper.GenerateCode(4);
// 将验证码存入Session,键名自定义
context.Session["VerifyCode"] = code;
// 设置图片宽度和高度
int width = 100;
int height = 40;
using (Bitmap bitmap = new Bitmap(width, height))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
// 设置背景色为白色
g.Clear(Color.White);
// 绘制验证码文字
Font font = new Font("Arial", 20, FontStyle.Bold);
SolidBrush brush = new SolidBrush(Color.Black);
g.DrawString(code, font, brush, 10, 5);
// 添加干扰线
Random random = new Random();
for (int i = 0; i < 5; 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.Gray, 1), x1, y1, x2, y2);
}
// 添加干扰点
for (int i = 0; i < 100; i++)
{
int x = random.Next(width);
int y = random.Next(height);
bitmap.SetPixel(x, y, Color.Gray);
}
}
// 设置输出格式为JPEG
context.Response.ContentType = "image/jpeg";
// 将图片保存到输出流
bitmap.Save(context.Response.OutputStream, ImageFormat.Jpeg);
}
}
public bool IsReusable
{
get { return false; }
}
}
3. 配置HttpHandler
我们需要在Web.config中注册这个Handler,让请求可以映射到对应的处理逻辑。
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.8" />
<httpRuntime targetFramework="4.8" />
</system.web>
<system.webServer>
<handlers>
<add name="VerifyCodeHandler" path="VerifyCode.aspx" verb="GET" type="VerifyCodeHandler" />
</handlers>
</system.webServer>
</configuration>
4. 前端页面展示与校验
前端页面中通过img标签引用Handler的地址展示验证码,用户输入后提交到后端进行校验。
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="WebApplication.Login" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>登录页面</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<label>验证码:</label>
<input type="text" id="txtCode" name="txtCode" />
<img src="VerifyCode.aspx" onclick="this.src='VerifyCode.aspx?t='+new Date().getTime()" alt="验证码" />
<p>点击图片可刷新验证码</p>
<asp:Button ID="btnSubmit" runat="server" Text="提交" OnClick="btnSubmit_Click" />
<asp:Label ID="lblMsg" runat="server" ForeColor="Red"></asp:Label>
</div>
</form>
</body>
</html>
后端校验逻辑如下,对比用户输入的验证码和Session中存储的值,注意忽略大小写。
using System;
using System.Web.UI;
namespace WebApplication
{
public partial class Login : Page
{
protected void btnSubmit_Click(object sender, EventArgs e)
{
string inputCode = txtCode.Text.Trim();
string sessionCode = Session["VerifyCode"] as string;
if (string.IsNullOrEmpty(sessionCode))
{
lblMsg.Text = "验证码已过期,请刷新后重试";
return;
}
if (inputCode.Equals(sessionCode, StringComparison.OrdinalIgnoreCase))
{
lblMsg.Text = "验证码校验通过";
// 后续业务逻辑处理
}
else
{
lblMsg.Text = "验证码输入错误,请重新输入";
}
}
}
}
注意事项
- 验证码存储建议使用Session,避免使用Cookie存储导致客户端可篡改
- 生成验证码时添加干扰线和干扰点,提升机器识别的难度
- 前端刷新验证码时添加随机参数,避免浏览器缓存导致验证码不更新
- 校验完成后可以清空Session中的验证码,避免重复使用
ASP.NET验证码C#HttpHandler修改时间:2026-07-09 17:33:31