Cookie 是伺服器發送至瀏覽器的小型文本數據,瀏覽器自動攜帶於後續請求中。核心屬性:
| 屬性 | 說明 | 安全影響 |
|---|---|---|
| Name/Value | 鍵值對,Value 建議 URL 編碼 | 勿存敏感明文 |
| Domain | 生效域名,預設為設定頁面域名 | 子域共享需顯式設定 `.example.com` |
| Path | 生效路徑,預設 `/` | 限制路徑減少暴露 |
| Expires/Max-Age | 過期時間,缺失則為會話級(關閉瀏覽器失效) | 持久化追蹤風險 |
| Secure | 僅 HTTPS 傳輸 | 生產環境必開 |
| HttpOnly | JavaScript 不可讀取 (`document.cookie` 不可見) | 防 XSS 竊取,認證 Cookie 必開 |
| SameSite | Strict/Lax/None(跨站請求攜帶策略) | 防 CSRF,現代預設 Lax |
protected void WriteCookie_Click(object sender, EventArgs e)
{
var cookie = new HttpCookie("UserPreferences")
{
Value = HttpUtility.UrlEncode("語言:繁體中文;主題:深色模式"),
Expires = DateTime.Now.AddDays(30), // 持久化 30 天
HttpOnly = true, // 防 XSS
Secure = Request.IsSecureConnection, // 僅 HTTPS
SameSite = SameSiteMode.Lax, // CSRF 保護
Path = "/" // 全站有效
};
// 子域共享:cookie.Domain = ".example.com";
Response.Cookies.Add(cookie);
// 多值 Cookie(單一 Cookie 存多鍵值,節省大小/數量限制)
var multi = new HttpCookie("UserProfile");
multi.Values["Theme"] = "Dark";
multi.Values["Lang"] = "zh-TW";
multi.Values["FontSize"] = "14";
multi.Expires = DateTime.Now.AddDays(30);
Response.Cookies.Add(multi);
}
protected void ReadCookie_Click(object sender, EventArgs e)
{
// 單值
if (Request.Cookies["UserPreferences"] != null)
{
string value = HttpUtility.UrlDecode(Request.Cookies["UserPreferences"].Value);
txtOutput.Text = value;
}
// 多值
if (Request.Cookies["UserProfile"] != null)
{
var cookie = Request.Cookies["UserProfile"];
string theme = cookie.Values["Theme"];
string lang = cookie.Values["Lang"];
// ...
}
// 遍歷所有
foreach (string key in Request.Cookies.AllKeys)
{
var c = Request.Cookies[key];
// 處理...
}
}
protected void DeleteCookie_Click(object sender, EventArgs e)
{
// 設定過期時間為過去
var cookie = new HttpCookie("UserPreferences")
{
Expires = DateTime.Now.AddDays(-1),
Path = "/", // 必須與建立時 Path 一致
Domain = ".example.com" // 若建立時指定 Domain,刪除時也需指定
};
Response.Cookies.Add(cookie);
}
const CookieUtil = {
// 寫入
set(name, value, days = 30, options = {}) {
let expires = "";
if (days) {
const date = new Date();
date.setTime(date.getTime() + days * 864e5);
expires = `; expires=${date.toUTCString()}`;
}
const secure = options.secure ? "; secure" : "";
const sameSite = options.sameSite ? `; samesite=${options.sameSite}` : "; samesite=lax";
const httpOnly = ""; // JS 無法設定 HttpOnly
const path = options.path ? `; path=${options.path}` : "; path=/";
const domain = options.domain ? `; domain=${options.domain}` : "";
document.cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}${expires}${path}${domain}${secure}${sameSite}`;
},
// 讀取
get(name) {
const nameEQ = encodeURIComponent(name) + "=";
const cookies = document.cookie.split(';');
for (let cookie of cookies) {
cookie = cookie.trim();
if (cookie.indexOf(nameEQ) === 0)
return decodeURIComponent(cookie.substring(nameEQ.length));
}
return null;
},
// 刪除
remove(name, options = {}) {
this.set(name, "", -1, options);
},
// 獲取所有
getAll() {
const result = {};
document.cookie.split(';').forEach(cookie => {
const [key, ...val] = cookie.trim().split('=');
result[decodeURIComponent(key)] = decodeURIComponent(val.join('='));
});
return result;
}
};
// 使用範例
CookieUtil.set('theme', 'dark', 365, { sameSite: 'strict', secure: true });
const theme = CookieUtil.get('theme');
CookieUtil.remove('theme');
// 寫入
document.cookie = "username=John; expires=Fri, 31 Dec 2025 23:59:59 GMT; path=/; secure; samesite=lax";
// 讀取(需自行解析)
function getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
}
// 刪除
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
// 寫入
Response.Cookies.Append("theme", "dark", new CookieOptions
{
Expires = DateTimeOffset.Now.AddYears(1),
HttpOnly = true,
Secure = true,
SameSite = SameSiteMode.Lax,
Path = "/",
IsEssential = true // GDPR 必要性標記
});
// 讀取
string theme = Request.Cookies["theme"];
// 刪除
Response.Cookies.Delete("theme", new CookieOptions { Path = "/" });
Cookie 是 HTTP 無狀態協議上的狀態載體。掌握其屬性語義、跨域限制、安全屬性組合,是 Web 開發者的基本功。現代開發傾向:認證用 JWT/Session+Redis,偏好設定用 LocalStorage/IndexedDB,Cookie 專注於身份識別與安全傳輸。