.ashx 實作 IHttpHandler,無 Page 基類,所有內建物件需透過 context 參數存取:
context.Request → HttpRequest (含 Cookies 集合)context.Response → HttpResponse (含 Cookies 集合、AppendCookie)public void ProcessRequest(HttpContext context) {
string validateNum = GenerateValidateCode(); // 假設產生驗證碼
HttpCookie cookie = new HttpCookie("validate");
cookie["validate"] = validateNum; // 子鍵值
// cookie.Value = validateNum; // 或直接用 Value (單值)
cookie.Expires = DateTime.Now.AddMinutes(20); // 設定過期時間(必須,否則為 Session Cookie)
cookie.HttpOnly = true; // 防 XSS,客戶端 JS 不可讀
cookie.Secure = context.Request.IsSecureConnection; // 僅 HTTPS 傳輸
context.Response.AppendCookie(cookie); // 或 context.Response.Cookies.Add(cookie)
// 輸出圖片/JSON 等...
}
public void ProcessRequest(HttpContext context) {
string validate = null;
// 方式一:直接存取 Value (單值 Cookie)
if (context.Request.Cookies["validate"] != null) {
validate = context.Request.Cookies["validate"].Value;
}
// 方式二:存取子鍵 (多值 Cookie)
// if (context.Request.Cookies["validate"] != null) {
// validate = context.Request.Cookies["validate"]["validate"];
// }
// 驗證邏輯...
if (validate == userInput) { /* 通過 */ }
}
// 設定過期時間為過去時間
HttpCookie cookie = new HttpCookie("validate");
cookie.Expires = DateTime.Now.AddDays(-1);
context.Response.AppendCookie(cookie);
| 屬性 | 說明 | 建議設定 |
|---|---|---|
| Expires | 過期日期時間 | 必設,否則瀏覽器關閉即失效 |
| Domain | 適用域名 | 跨子域共享時設定 (如 .example.com) |
| Path | 適用路徑 | 預設 "/",通常無需修改 |
| HttpOnly | 禁止 JS 讀取 | true (防 XSS) |
| Secure | 僅 HTTPS 傳輸 | true (生產環境必開) |
| SameSite | 跨站傳送策略 | Lax / Strict / None (需 .NET 4.7.2+) |
public class ValidateHandler : IHttpHandler {
public void ProcessRequest(HttpContext context) {
context.Response.ContentType = "text/plain";
if (context.Request.HttpMethod == "POST") {
// 寫入驗證碼
string code = new Random().Next(1000, 9999).ToString();
var cookie = new HttpCookie("validate") {
Value = code,
Expires = DateTime.Now.AddMinutes(10),
HttpOnly = true,
Secure = context.Request.IsSecureConnection
};
context.Response.AppendCookie(cookie);
context.Response.Write("OK:" + code); // 測試用,實際應回傳圖片
} else {
// 驗證
string input = context.Request.QueryString["code"];
string stored = context.Request.Cookies["validate"]?.Value;
context.Response.Write(stored == input ? "VALID" : "INVALID");
}
}
public bool IsReusable => false;
}