依據 Netscape 標準,HTTP Cookie 格式為:
Set-Cookie: NAME=VALUE; Expires=DATE; Path=PATH; Domain=DOMAIN_NAME; SECURE
| 屬性 | 說明 | 關鍵點 |
|---|---|---|
| Name=Value | 必填,鍵值對 | 不可含分號、逗號、空格 |
| Expires | 過期時間 (GMT 格式) | 省略則為 Session Cookie,瀏覽器關閉即失效 |
| Domain | 可讀取該 Cookie 的域 | 格式 .example.com 可跨子域;預設為發送伺服器域 |
| Path | 可存取的 URL 路徑前綴 | / 代表全站;預設為請求資源路徑 |
| Secure | 僅 HTTPS 傳輸 | 防止明文傳輸被竊聽 |
| HttpOnly | 禁止 JS 存取 (現代標準) | 緩解 XSS 攻擊,ASP.NET HttpCookie.HttpOnly 預設 true |
Request.Cookies / Response.Cookies)。HttpWebRequest 客戶端模擬登入場景。轉換關鍵:CookieContainer.GetCookies(uri) → CookieCollection;CookieCollection[index] → Cookie。
public static class CookieHelper
{
/// 寫入 Cookie (支援跨子域)
public static bool Set(string name, string value, int expireDays, string domain = null)
{
try
{
var cookie = new HttpCookie(name, value)
{
Expires = DateTime.Now.AddDays(expireDays),
HttpOnly = true, // 安全預設
// Secure = true, // 僅 HTTPS 環境啟用
};
if (!string.IsNullOrEmpty(domain)) cookie.Domain = domain; // 如 ".example.com"
HttpContext.Current.Response.Cookies.Add(cookie);
return true;
}
catch { return false; }
}
/// 讀取 Cookie 值
public static string Get(string name)
{
var cookie = HttpContext.Current.Request.Cookies[name];
return cookie?.Value; // 回傳 null 或值
}
/// 刪除 Cookie (設定過期時間為過去)
public static bool Remove(string name, string domain = null)
{
try
{
var cookie = new HttpCookie(name) { Expires = DateTime.Now.AddDays(-1) };
if (!string.IsNullOrEmpty(domain)) cookie.Domain = domain;
HttpContext.Current.Response.Cookies.Add(cookie);
return true;
}
catch { return false; }
}
}
var container = new CookieContainer();
// 1. 從回應標頭手動解析並加入 (注意 Domain 格式陷阱)
string setCookieHeader = response.Headers.Get("Set-Cookie");
// ⚠️ SetCookies 的 uri 不能與 cookie Domain 完全相同 (如 .google.com)
// 解決:使用具體子域 uri,如 new Uri("https://www.google.com")
container.SetCookies(new Uri("https://www.google.com"), setCookieHeader);
// 2. 取得指定網站所有 Cookie 字串 (供後續請求帶入)
string cookieHeader = container.GetCookieHeader(new Uri("https://www.google.com"));
// 3. 手動新增單一 Cookie
container.Add(new Uri("https://api.example.com"), new Cookie("token", "abc123") { Domain = ".example.com" });
.example.com),且 SetCookies 的 URI 不能是裸域 (需 www.example.com)。HttpUtility.UrlEncode / UrlDecode。cookie.SameSite = SameSiteMode.Lax 防禦 CSRF。