Cookie 是 HTTP 無狀態協定中維持狀態的關鍵機制。ASP.NET 提供 `HttpCookie`、`Request.Cookies`、`Response.Cookies` 等 API。本文系統整理 Cookie 寫入/讀取/修改/刪除、多值 Cookie、跨子域共享、安全性屬性 (HttpOnly、Secure、SameSite) 設定,並提供最佳實務封裝類別。
// 方式 1:Response.Cookies 集合
Response.Cookies["UserName"].Value = "Mike";
Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(30); // 持久化 30 天
// 方式 2:HttpCookie 物件 (推薦,可設定更多屬性)
HttpCookie cookie = new HttpCookie("UserName", "Mike");
cookie.Expires = DateTime.Now.AddDays(30);
cookie.HttpOnly = true; // 防止 JavaScript 存取 (防 XSS)
cookie.Secure = true; // 僅 HTTPS 傳輸 (需網站已啟用 HTTPS)
cookie.SameSite = SameSiteMode.Lax; // CSRF 保護: Strict/Lax/None
cookie.Domain = ".example.com"; // 跨子域共享 (見下文)
Response.Cookies.Add(cookie);
if (Request.Cookies["UserName"] != null)
{
string userName = Request.Cookies["UserName"].Value; // 自動 URL 解碼
// 使用 userName...
}
HttpCookie cookie = new HttpCookie("UserName");
cookie.Expires = DateTime.Now.AddDays(-1);
cookie.Domain = ".example.com"; // 必須與寫入時相同 Domain/Path
Response.Cookies.Add(cookie);
適用於關聯性強的小資料 (如使用者偏好設定),避免建立過多 Cookie (瀏覽器限制每域名約 50-180 個、總大小 4KB)。
HttpCookie cookie = new HttpCookie("UserPrefs");
cookie.Values["Theme"] = "Dark";
cookie.Values["Lang"] = "zh-TW";
cookie.Values["PageSize"] = "20";
cookie.Expires = DateTime.Now.AddDays(365);
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);
if (Request.Cookies["UserPrefs"] != null)
{
string theme = Request.Cookies["UserPrefs"]["Theme"]; // 直接存取子鍵
string lang = Request.Cookies["UserPrefs"]["Lang"];
// 或遍歷所有子鍵
foreach (string key in Request.Cookies["UserPrefs"].Values.AllKeys)
{
string val = Request.Cookies["UserPrefs"][key];
}
}
HttpCookie cookie = Request.Cookies["UserPrefs"];
if (cookie != null)
{
cookie.Values["Theme"] = "Light"; // 修改
cookie.Expires = DateTime.Now.AddDays(365); // 必須重新設定過期時間
Response.Cookies.Add(cookie);
}
HttpCookie cookie = Request.Cookies["UserPrefs"];
if (cookie != null)
{
cookie.Values.Remove("Lang");
cookie.Expires = DateTime.Now.AddDays(365);
Response.Cookies.Add(cookie);
}
主站 `www.example.com`、子站 `api.example.com`、`shop.example.com` 共享 Cookie:
// 寫入時設定 Domain 為根域名 (前面加 .)
cookie.Domain = ".example.com"; // 注意前面的點
cookie.Path = "/"; // 路徑設為根目錄
限制:無法跨不同頂級域名 (如 `example.com` 與 `other.com`)。需搭配 SSO (Single Sign-On) 架構。
HttpCookie cookie = new HttpCookie("AuthToken", tokenValue)
{
HttpOnly = true, // 【必須】防止 XSS 竊取 Cookie (JS 無法讀取 document.cookie)
Secure = true, // 【必須若 HTTPS】僅 HTTPS 傳輸,防止中間人攻擊
SameSite = SameSiteMode.Lax, // 【推薦】CSRF 保護:Lax (預設)、Strict、None (需 Secure=true)
Expires = DateTime.Now.AddHours(2), // 存活期
Path = "/", // 整站有效
Domain = ".example.com" // 跨子域
};
Response.Cookies.Add(cookie);
| 模式 | 行為 | 適用場景 |
|---|---|---|
| Strict | 完全禁止跨站攜帶 Cookie (含連結點擊) | 高安全需求 (銀行、後台) |
| Lax (預設) | 允許安全跨站請求 (GET 導航、連結),禁止 POST/iframe/圖片請求 | 大多數網站、平衡安全與體驗 |
| None | 允許所有跨站請求,**必須搭配 Secure=true** | 跨域 API、第三方嵌入、SSO |
// ASP.NET Core 寫入
Response.Cookies.Append("key", "value", new CookieOptions
{
HttpOnly = true,
Secure = true,
SameSite = SameSiteMode.Lax,
Expires = DateTimeOffset.UtcNow.AddDays(30),
Domain = ".example.com",
Path = "/"
});
// ASP.NET Core 讀取
string value = Request.Cookies["key"];
// ASP.NET Core 刪除
Response.Cookies.Delete("key", new CookieOptions { Domain = ".example.com", Path = "/" });
public static class CookieHelper
{
public static void Set(string key, string value, int? expireDays = null, bool httpOnly = true, bool secure = true, SameSiteMode sameSite = SameSiteMode.Lax, string domain = null, string path = "/")
{
HttpCookie cookie = new HttpCookie(key, value)
{
HttpOnly = httpOnly,
Secure = secure,
SameSite = sameSite,
Path = path
};
if (expireDays.HasValue) cookie.Expires = DateTime.Now.AddDays(expireDays.Value);
if (!string.IsNullOrEmpty(domain)) cookie.Domain = domain;
HttpContext.Current.Response.Cookies.Add(cookie);
}
public static void SetMulti(string key, Dictionary values, int? expireDays = null, bool httpOnly = true, bool secure = true, SameSiteMode sameSite = SameSiteMode.Lax, string domain = null, string path = "/")
{
HttpCookie cookie = new HttpCookie(key) { HttpOnly = httpOnly, Secure = secure, SameSite = sameSite, Path = path };
if (expireDays.HasValue) cookie.Expires = DateTime.Now.AddDays(expireDays.Value);
if (!string.IsNullOrEmpty(domain)) cookie.Domain = domain;
foreach (var kv in values) cookie.Values[kv.Key] = kv.Value;
HttpContext.Current.Response.Cookies.Add(cookie);
}
public static string Get(string key) => HttpContext.Current.Request.Cookies[key]?.Value;
public static string GetSubKey(string cookieKey, string subKey) => HttpContext.Current.Request.Cookies[cookieKey]?[subKey];
public static void Remove(string key, string domain = null, string path = "/")
{
HttpCookie cookie = new HttpCookie(key) { Expires = DateTime.Now.AddDays(-1), Path = path };
if (!string.IsNullOrEmpty(domain)) cookie.Domain = domain;
HttpContext.Current.Response.Cookies.Add(cookie);
}
public static void RemoveSubKey(string cookieKey, string subKey, string domain = null, string path = "/")
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[cookieKey];
if (cookie != null)
{
cookie.Values.Remove(subKey);
cookie.Expires = DateTime.Now.AddDays(365); // 保持原有效期
cookie.Path = path;
if (!string.IsNullOrEmpty(domain)) cookie.Domain = domain;
HttpContext.Current.Response.Cookies.Add(cookie);
}
}
}
總結:ASP.NET Cookie 操作核心在於 `HttpCookie` 物件屬性正確設定。現代 Web 應用**必須**設定 `HttpOnly=true`、`Secure=true` (HTTPS)、`SameSite=Lax`。多值 Cookie 適合小型關聯資料。跨子域共享設定 `Domain=.parent.com`。封裝 `CookieHelper` 統一管理,避免重複程式碼與遺漏安全屬性。