萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET 使用 Cookie 傳遞參數:寫入、讀取、刪除與安全性實務

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 僅存識別碼

加密 Cookie 範例 (MachineKey)

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));

GDPR / 隱私法規合規

  • 首次造訪顯示 Cookie 同意橫幅,分類必要/偏好/統計/行銷。
  • 提供「拒絕非必要 Cookie」選項,拒絕時不寫入對應 Cookie。
  • 隱私權政策說明 Cookie 用途、保存期限、第三方共享對象。

常見問題

  1. Cookie 未送達:檢查 `Domain`/`Path`/`Secure`/`SameSite` 設定是否與請求網址匹配。
  2. 400 Bad Request - Cookie 大小超限:單一 Cookie ≤ 4KB,總數 ≤ 20~50/域名,改用 Session/資料庫存大量資料。
  3. 跨子網域共享:設定 `Domain = ".example.com"` (前綴點號),所有子網域可讀寫。

善用 Cookie 傳遞輕量狀態,但務必遵循「最小權限、加密敏感、合規透明」原則,才能兼顧功能與安全。

copyright © 萬盛學電腦網 all rights reserved