Cookie 是 HTTP 無狀態特性下在客戶端保存少量資料的標準機制。ASP.NET 提供 `HttpCookie`、`Request.Cookies`、`Response.Cookies` 簡單 API,但實務上需注意編碼、安全性旗標、SameSite、GDPR 合規等細節。本文提供完整操作範例與安全強化清單。
// 寫入
var cookie = new HttpCookie("UserPrefs", "theme=dark&lang=zh-TW") {
Expires = DateTime.Now.AddDays(30), // 持久化 30 天
HttpOnly = true, // 防 XSS 竊取
Secure = Request.IsSecureConnection, // 僅 HTTPS 傳輸
SameSite = SameSiteMode.Lax, // CSRF 防護 (需 .NET 4.7.2+)
Path = "/" // 全站可用
};
Response.Cookies.Add(cookie);
// 讀取
if (Request.Cookies["UserPrefs"] is HttpCookie c) {
string value = c.Value; // "theme=dark&lang=zh-TW"
// 解析...
}
// 刪除 (設定過期)
Response.Cookies["UserPrefs"].Expires = DateTime.Now.AddDays(-1);
單一 Cookie 可存多組鍵值對,避免建立過多 Cookie:
var cookie = new HttpCookie("UserProfile") {
["UserId"] = "12345",
["DisplayName"] = "王小明",
["Theme"] = "dark"
};
cookie.Expires = DateTime.Now.AddDays(30);
Response.Cookies.Add(cookie);
// 讀取子鍵
string theme = Request.Cookies["UserProfile"]?["Theme"]; // "dark"
| 屬性/措施 | 目的 | 設定建議 |
|---|---|---|
| HttpOnly | 阻擋 JavaScript 讀取 (防 XSS) | `true` (預設 true,勿關閉) |
| Secure | 僅 HTTPS 傳輸 (防中間人) | `Request.IsSecureConnection` 或強制 `true` |
| SameSite | 控制跨站請求攜帶行為 (防 CSRF) | `Lax` (預設) / `Strict` / `None` (需 Secure) |
| Domain | 限定可存取的網域 | 生產環境明確設定 `.example.com`,避免子網域洩漏 |
| Path | 限定路徑範圍 | 預設 `/`,若只需特定路徑可縮小 |
| 加密/簽名 | 防竄改、防洩漏敏感資訊 | 使用 `MachineKey.Protect/Unprotect` 或 `AspNetCore.DataProtection` |
| 不存敏感資料 | 原則上不存密碼、Token、PII | 改用 Server-side Session/Token 存儲,Cookie 僅存識別碼 |
public string Protect(string plainText) {
byte[] data = Encoding.UTF8.GetBytes(plainText);
byte[] protectedData = MachineKey.Protect(data, "CookieProtection");
return Convert.ToBase64String(protectedData);
}
public string Unprotect(string protectedText) {
byte[] data = Convert.FromBase64String(protectedText);
byte[] plainData = MachineKey.Unprotect(data, "CookieProtection");
return Encoding.UTF8.GetString(plainData);
}
// 寫入加密值
cookie.Value = Protect(JsonConvert.SerializeObject(userProfile));
善用 Cookie 傳遞輕量狀態,但務必遵循「最小權限、加密敏感、合規透明」原則,才能兼顧功能與安全。