實作 IHttpHandler + IRequiresSessionState,使用 GDI+ 繪製含干擾線、扭曲字元的驗證碼圖片,驗證碼存入 Session 供後續驗證。
<%@ WebHandler Language="C#" Class="CaptchaHandler" %>
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
using System.Web.SessionState;
public class CaptchaHandler : IHttpHandler, IRequiresSessionState
{
private readonly Random _rnd = new Random();
private const string Chars = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"; // 排除易混淆字元
public void ProcessRequest(HttpContext context)
{
string code = GenerateCode(6);
context.Session["CaptchaCode"] = code; // 必須實作 IRequiresSessionState
using (var bmp = new Bitmap(130, 45))
using (var g = Graphics.FromImage(bmp))
{
g.Clear(Color.White);
g.DrawRectangle(Pens.LightGray, 0, 0, bmp.Width - 1, bmp.Height - 1);
// 干擾線
for (int i = 0; i < 15; i++)
g.DrawLine(Pens.LightGray,
_rnd.Next(bmp.Width), _rnd.Next(bmp.Height),
_rnd.Next(bmp.Width), _rnd.Next(bmp.Height));
// 繪製字元 (隨機字體、大小、顏色、旋轉)
Font[] fonts = { new Font("Arial", 22, FontStyle.Bold),
new Font("Verdana", 22, FontStyle.Italic),
new Font("Tahoma", 22, FontStyle.Bold | FontStyle.Italic) };
Brush[] brushes = { Brushes.Black, Brushes.DarkBlue, Brushes.DarkGreen,
Brushes.Maroon, Brushes.Purple, Brushes.Teal };
for (int i = 0; i < code.Length; i++)
{
var font = fonts[_rnd.Next(fonts.Length)];
var brush = brushes[_rnd.Next(brushes.Length)];
float angle = _rnd.Next(-15, 15);
float x = i * 20 + _rnd.Next(3);
float y = _rnd.Next(5);
g.TranslateTransform(x, y);
g.RotateTransform(angle);
g.DrawString(code[i].ToString(), font, brush, 0, 0);
g.ResetTransform();
}
context.Response.ContentType = "image/jpeg";
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
using (var ms = new MemoryStream())
{
bmp.Save(ms, ImageFormat.Jpeg);
context.Response.BinaryWrite(ms.ToArray());
}
}
}
private string GenerateCode(int length)
{
char[] buf = new char[length];
for (int i = 0; i < length; i++)
buf[i] = Chars[_rnd.Next(Chars.Length)];
return new string(buf);
}
public bool IsReusable => false;
}
<img id="captcha" src="CaptchaHandler.ashx" alt="驗證碼" style="vertical-align:middle; cursor:pointer;"
onclick="this.src='CaptchaHandler.ashx?' + Date.now()" />
<input type="text" id="txtCaptcha" maxlength="6" />
protected void BtnSubmit_Click(object sender, EventArgs e)
{
string input = txtCaptcha.Text.Trim().ToUpper();
string sessionCode = (Session["CaptchaCode"] ?? "").ToString().ToUpper();
Session.Remove("CaptchaCode"); // 一次性使用
if (string.Equals(input, sessionCode, StringComparison.OrdinalIgnoreCase))
{
// 通過
}
else
{
// 失敗
}
}