在 ASP.NET 開發中,Cookie 是實現用戶狀態保持、記錄偏好設定等常用手段。本文整理了四種在伺服器端寫入 Cookie 的典型寫法,並附上對應的讀取範例,供開發者快速參考。
HttpCookie.Values 集合存放多組鍵值此法適合需要在單一 Cookie 下儲存多個相關欄位的情境。
// 建立 Cookie 物件
HttpCookie myCookie = new HttpCookie("userrole");
// 寫入多組鍵值
myCookie.Values["a"] = "a";
myCookie.Values["b"] = "b";
// 設定過期時間(1 天後)
myCookie.Expires = DateTime.Now.AddDays(1);
// 送出至用戶端
Response.Cookies.Add(myCookie);
// 讀取範例
Response.Write(Request.Cookies["userrole"].Values["a"].ToString());
Values 集合,但讀取方式略有不同寫入邏輯與方法一相同,讀取時先取得 HttpCookie 物件,再從中取值,程式碼較具可讀性。
HttpCookie myCookie = new HttpCookie("userrole");
myCookie.Values["a"] = "a";
myCookie.Values["b"] = "b";
myCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(myCookie);
// 讀取
HttpCookie cookie = Request.Cookies["userrole"];
Response.Write(cookie.Values["a"].ToString());
Response.Write(cookie.Values["b"].ToString());
HttpCookie.Value 屬性存放單一字串若只需儲存一個簡單字串,可直接指定 Value 屬性,結構更單純。
HttpCookie myCookie = new HttpCookie("userrole");
myCookie.Value = "a"; // 單一值
Response.Cookies.Add(myCookie);
// 讀取
Response.Write(Request.Cookies["userrole"].Value);
HttpContext.Current.Response.Cookies 一行式寫入適合快速原型開發,但實際專案建議拆分為明確步驟,方便維護與除錯。
HttpContext.Current.Response.Cookies.Add(new HttpCookie("userrole", "超級管理員"));
Response.Cookies["userrole"].Value = "超級管理員";
HttpCookie cookie = Request.Cookies["userrole"];
Response.Write(cookie.Value);
Expires,否則 Cookie 為 Session 級別,瀏覽器關閉即失效。Request.Cookies["name"] 是否為 null,避免拋出 NullReferenceException。