原始碼為單一 .ashx 處理程式,產生驗證碼並直接輸出圖片,存在三大問題:
ValidateCode 類別,暴露屬性配置(長度、字元集、字體、尺寸、顏色、干擾線/點密度等)。GetString()、GetBitmap()、GetByteArray()、GetStream()。public class ValidateCodeHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
var vc = new ValidateCode { Length = 4, FontSize = 22, Chaos = true };
context.Session["ValidateCode"] = vc.GetString(); // 1. 取字串存 Session
context.Response.BinaryWrite(vc.GetByteArray()); // 2. 取位元組輸出圖片
context.Response.ContentType = "image/bmp";
}
public bool IsReusable => false;
}
public class ValidateCode
{
// 可配置屬性
public int Length { get; set; } = 4;
public string CodeSerial { get; set; } = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public int FontSize { get; set; } = 20;
public Color BackColor { get; set; } = Color.White;
public Color[] FontColors { get; set; } = { Color.Black, Color.Blue, Color.Red };
public bool Chaos { get; set; } = true; // 干擾線
public int Padding { get; set; } = 2;
// 核心產生邏輯
private string GenerateCode() { /* 隨機取 CodeSerial 字元 */ }
private Bitmap CreateImage(string code) { /* GDI+ 繪製文字、干擾線、噪點 */ }
// 多種輸出
public string GetString() => GenerateCode();
public Bitmap GetBitmap() => CreateImage(GenerateCode());
public byte[] GetByteArray() { using (var ms = new MemoryStream()) { GetBitmap().Save(ms, ImageFormat.Bmp); return ms.ToArray(); } }
public Stream GetStream() { var ms = new MemoryStream(); GetBitmap().Save(ms, ImageFormat.Bmp); ms.Position = 0; return ms; }
}
MyLib/ ├─ ValidateCode.cs // 核心類別 ├─ ValidateCodeHandler.ashx // Web 專案引用的 Handler 範例 └─ Properties/AssemblyInfo.cs
編譯為 MyLib.dll,任何專案引用即可使用,WinForm 呼叫 GetBitmap() 顯示於 PictureBox,Web 呼叫 GetByteArray() 配合 BinaryWrite。
完整 VS2010 方案(含 old/new 對比版本):
/201012/yuanma/yanzhengma.rar
「拿來即用」不可取,但「過度設計」同樣有害。專案緊急時,能跑通即可;有餘力時,花 30 分鐘將通用邏輯抽離成元件,長遠受益。關鍵在於思考後再決定,而非盲目複製。