結合上篇隨機字串工具,實作完整驗證碼功能:產生圖形驗證碼、Session 儲存、前端驗證。
建立 Captcha.ashx 實作 IRequiresSessionState:
public void ProcessRequest(HttpContext context) {
string code = CharacterUtility.GetRandomString(4, true, true, false, false);
context.Session["Captcha"] = code;
// 使用 GDI+ 繪製圖片並輸出 JPEG
}
public ActionResult CaptchaDemo() { return View(); }
[HttpPost]
public JsonResult ValidateCaptcha(string inputCode) {
string sessionCode = Session["Captcha"] as string;
return Json(new { success = !string.IsNullOrEmpty(sessionCode) && sessionCode.Equals(inputCode, StringComparison.OrdinalIgnoreCase) });
}
使用 <img src="Captcha.ashx" /> 顯示驗證碼,點擊圖片重新整理;AJAX 提交輸入碼至 ValidateCaptcha 驗證。
完整示範從圖片產生、Session 管理、前後端驗證的驗證碼完整流程。