萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET HTTP Handler 動態產生驗證碼圖片 (含 Session 驗證)

實作 IHttpHandler + IRequiresSessionState,使用 GDI+ 繪製含干擾線、扭曲字元的驗證碼圖片,驗證碼存入 Session 供後續驗證。

完整 Handler 程式碼

<%@ 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
    {
        // 失敗
    }
}

部署與安全強化

  • IIS 應用程式集區身分需具備 GDI+ 權限 (通常預設即可)。
  • 生產環境建議加入 速率限制 (同 IP 分鐘最多請求 N 次),防止暴力消耗 CPU。
  • 現代替代:reCAPTCHA v3 (無感知)、hCaptcha、Turnstile (Cloudflare) — 免去圖片產生維護,安全性更高。
copyright © 萬盛學電腦網 all rights reserved