萬盛學電腦網

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

ASP.NET 動態產生驗證碼圖片 (Bitmap + GDI+)

以 System.Drawing 命名空間繪製含雜訊干擾的驗證碼圖片,輸出為 JPEG 串流直接回傳給瀏覽器,並將驗證碼存入 Session 驗證。

Generic Handler 實作 (.ashx)

<%@ 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"); // 單次使用即銷毀
}

部署與效能提醒

  • IIS 預設不允許非互動式帳號存取 GDI+,若出現「GDI+ 一般錯誤」,請確認應用程式集區身分為 ApplicationPoolIdentity 或具備桌面互動權限。
  • 高併發下建議改用 MemoryStream 而非直接寫入 Response.OutputStream,或採用 SkiaSharp、ImageSharp 等跨平台繪圖庫 (支援 .NET Core / Linux 容器)。
  • 現代專案建議改用 reCAPTCHA v3 / hCaptcha 等行為分析驗證,完全免去圖片產生與維護成本。
copyright © 萬盛學電腦網 all rights reserved