萬盛學電腦網

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

ASP.NET 與 JavaScript Cookie 操作完整指南:讀寫、屬性、跨域與安全

Cookie 基礎知識

Cookie 是伺服器發送至瀏覽器的小型文本數據,瀏覽器自動攜帶於後續請求中。核心屬性:

屬性說明安全影響
Name/Value鍵值對,Value 建議 URL 編碼勿存敏感明文
Domain生效域名,預設為設定頁面域名子域共享需顯式設定 `.example.com`
Path生效路徑,預設 `/`限制路徑減少暴露
Expires/Max-Age過期時間,缺失則為會話級(關閉瀏覽器失效)持久化追蹤風險
Secure僅 HTTPS 傳輸生產環境必開
HttpOnlyJavaScript 不可讀取 (`document.cookie` 不可見)防 XSS 竊取,認證 Cookie 必開
SameSiteStrict/Lax/None(跨站請求攜帶策略)防 CSRF,現代預設 Lax

ASP.NET 伺服器端操作

寫入 Cookie

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

讀取 Cookie

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];
        // 處理...
    }
}

刪除 Cookie

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

JavaScript 客戶端操作

封裝工具函數(推薦)

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=/";

跨域與子域共享

  • 同一主域不同子域:設定 `Domain = ".example.com"`(前綴點),`a.example.com` 寫入,`b.example.com` 可讀
  • 完全不同域:瀏覽器同源策略禁止,需使用:
      li>CORS + Credentials (`withCredentials: true` + `Access-Control-Allow-Credentials: true` + `Access-Control-Allow-Origin: 具體域名`)
    • 第三方 Cookie(Chrome 已預設阻擋,Safari/Firefox 限制中)
    • Server-to-Server 代理或 JWT Token 傳遞

安全最佳實踐

  1. 認證 Cookie 必須:`HttpOnly=true`、`Secure=true`、`SameSite=Strict/Lax`
  2. 敏感數據加密:`MachineKey.Protect` / `DataProtectionProvider` 加密後存 Cookie
  3. 大小控制:單 Cookie ≤ 4KB,單域 ≤ 50-180 個,超過會被瀏覽器清理
  4. 防範 CSRF:SameSite + AntiForgeryToken 雙重保障
  5. GDPR/隱私合規:明確同意、提供拒絕、資料可攜帶、刪除機制

ASP.NET Core 現代化寫法


// 寫入
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 專注於身份識別與安全傳輸。

copyright © 萬盛學電腦網 all rights reserved