以 System.Drawing 命名空間繪製含雜訊干擾的驗證碼圖片,輸出為 JPEG 串流直接回傳給瀏覽器,並將驗證碼存入 Session 驗證。
<%@ WebHandler Language="C#" Class="CaptchaHandler" %>
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web;
public class CaptchaHandler : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/jpeg";
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
using (Bitmap bmp = new Bitmap(100, 36))
using (Graphics g = Graphics.FromImage(bmp))
{
g.Clear(Color.White);
g.DrawRectangle(Pens.Gray, 0, 0, bmp.Width - 1, bmp.Height - 1);
// 畫雜訊線
Random r = new Random();
for (int i = 0; i < 20; i++)
g.DrawLine(Pens.LightGray, r.Next(bmp.Width), r.Next(bmp.Height),
r.Next(bmp.Width), r.Next(bmp.Height));
// 產生 4 碼驗證碼
string chars = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"; // 排除 0/O/1/I
string code = "";
for (int i = 0; i < 4; i++)
code += chars[r.Next(chars.Length)];
// 存入 Session
context.Session["CaptchaCode"] = code;
// 繪製文字 (隨機位置、字體、顏色)
Font[] fonts = { new Font("Arial", 18, FontStyle.Bold),
new Font("Verdana", 18, FontStyle.Italic) };
for (int i = 0; i < code.Length; i++)
{
g.DrawString(code[i].ToString(), fonts[r.Next(fonts.Length)],
new SolidBrush(Color.FromArgb(r.Next(100), r.Next(100), r.Next(100))),
i * 22 + r.Next(3), r.Next(6));
}
bmp.Save(context.Response.OutputStream, ImageFormat.Jpeg);
}
}
public bool IsReusable => false;
}
<img id="captchaImg" src="CaptchaHandler.ashx" style="cursor:pointer; vertical-align:middle;"
onclick="this.src='CaptchaHandler.ashx?' + Math.random()" />
<input type="text" id="txtCaptcha" maxlength="4" />
protected void BtnSubmit_Click(object sender, EventArgs e)
{
string userInput = txtCaptcha.Text.Trim().ToUpper();
string sessionCode = (Session["CaptchaCode"] ?? "").ToString().ToUpper();
if (userInput == sessionCode)
{
// 驗證通過
}
else
{
// 驗證失敗
}
Session.Remove("CaptchaCode"); // 單次使用即銷毀
}
ApplicationPoolIdentity 或具備桌面互動權限。Response.OutputStream,或採用 SkiaSharp、ImageSharp 等跨平台繪圖庫 (支援 .NET Core / Linux 容器)。