Cookie (HttpCookie的實(shí)例)提供了一種在 Web 應(yīng)用程序中存儲(chǔ)用戶特定信息的方法。例如,當(dāng)用戶訪問(wèn)您的站點(diǎn)時(shí),您可以使用Cookie 存儲(chǔ)用戶首選項(xiàng)或其他信息。當(dāng)該用戶再次訪問(wèn)您的網(wǎng)站時(shí),應(yīng)用程序便可以檢索以前存儲(chǔ)的信息。
ASP.NET中的cookie:創(chuàng)建Cookie方法 (1)
Response.Cookies["userName"].Value = “admin";
Response.Cookies[“userName”].Expires = DateTime.Now.AddDays(1);
//如果不設(shè)置失效時(shí)間,Cookie信息不會(huì)寫到用戶硬盤,瀏覽器關(guān)閉將會(huì)丟棄。
ASP.NET中的cookie:創(chuàng)建Cookie方法 (2)
HttpCookie aCookie = new HttpCookie(“l(fā)astVisit”);
//上一次訪問(wèn)時(shí)間
aCookie.Value = DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);
ASP.NET中的cookie:訪問(wèn)Cookie方法(1)
if(Request.Cookies["userName"] != null)
Label1.Text = Server.HtmlEncode(Request.Cookies["userName"].Value);
訪問(wèn)Cookie方法(2)
if(Request.Cookies["userName"] != null) {
HttpCookie aCookie = Request.Cookies["userName"];
Label1.Text = Server.HtmlEncode(aCookie.Value);
}
ASP.NET中的cookie:創(chuàng)建多值Cookie方法 (1)
Response.Cookies["userInfo"]["userName"] = “admin";
Response.Cookies["userInfo"]["lastVisit"] = DateTime.Now.ToString();
Response.Cookies["userInfo"].Expires = DateTime.Now.AddDays(1);
ASP.NET中的cookie:創(chuàng)建多值Cookie方法 (2)
HttpCookie aCookie = new HttpCookie("userInfo");
aCookie.Values["userName"] = “admin";
aCookie.Values["lastVisit"] = DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);
ASP.NET中的cookie:讀取多值Cookie
HttpCookie aCookie = Request.Cookies["userInfo"];
string userName=aCookie.Values[“userName”];
string lastVisit=aCookie.Values[“l(fā)astVisit”];
ASP.NET中的cookie:修改和刪除Cookie
不能直接修改或刪除Cookie,只能創(chuàng)建一個(gè)新的Cookie,發(fā)送到客戶端以實(shí)現(xiàn)修改或刪除Cookie。
