假設驗證碼生成頁面為 CheckCode.aspx,在登入頁面使用 <img> 標籤引用:
<img src="CheckCode.aspx" alt="驗證碼" />
private void btnLogin_Click(object sender, ImageClickEventArgs e)
{
// 1. 檢查 Cookie 是否啟用
if (Request.Cookies["CheckCode"] == null)
{
lblMessage.Text = "您的瀏覽器已禁用 Cookie,請啟用後再使用本系統。";
lblMessage.Visible = true;
return;
}
// 2. 比對驗證碼(不分大小寫)
string storedCode = Request.Cookies["CheckCode"].Value;
string inputCode = txtCheckCode.Text;
if (string.Compare(storedCode, inputCode, true) != 0)
{
lblMessage.Text = "驗證碼錯誤,請輸入正確的驗證碼。";
lblMessage.Visible = true;
return;
}
// 3. 驗證通過,執行登入邏輯
// ... 其他登入代碼 ...
}
CheckCode.aspx 需將生成的驗證碼寫入 Response.Cookies["CheckCode"].ValueHttpOnly = true 增加安全性Response.Cache.SetNoStore() 防止瀏覽器快取驗證碼圖片
用戶請求登入頁 → 瀏覽器載入 <img src="CheckCode.aspx">
↓
CheckCode.aspx 生成隨機碼 → 存入 Cookie → 輸出圖片二進位流
↓
用戶輸入驗證碼 → 點擊登入 → 後端比對 Cookie 值與輸入值
↓
比對成功 → 登入邏輯 / 比對失敗 → 顯示錯誤 → 重新整理驗證碼