Cookie (HttpCookie的執行個體)提供了一種在 Web 應用程式中儲存使用者特定資訊的方法。例如,當使用者訪問您的網站時,您可以使用 Cookie 儲存使用者喜好設定或其他資訊。當該使用者再次訪問您的網站時,應用程式便可以檢索以前儲存的資訊。
建立Cookie方法 (1)
Response.Cookies["userName"].Value = “admin";Response.Cookies[“userName”].Expires = DateTime.Now.AddDays(1);
//如果不設定失效時間,Cookie資訊不會寫到使用者硬碟,瀏覽器關閉將會丟棄。
建立Cookie方法 (2)
HttpCookie aCookie = new HttpCookie(“lastVisit”); //上一次訪問時間 aCookie.Value = DateTime.Now.ToString(); aCookie.Expires = DateTime.Now.AddDays(1); Response.Cookies.Add(aCookie);
訪問Cookie方法(1)
if(Request.Cookies["userName"] != null) Label1.Text = Server.HtmlEncode(Request.Cookies["userName"].Value);訪問Cookie方法(2) if(Request.Cookies["userName"] != null) { HttpCookie aCookie = Request.Cookies["userName"]; Label1.Text = Server.HtmlEncode(aCookie.Value); }
建立多值Cookie方法 (1)
Response.Cookies["userInfo"]["userName"] = “admin"; Response.Cookies["userInfo"]["lastVisit"] = DateTime.Now.ToString(); Response.Cookies["userInfo"].Expires = DateTime.Now.AddDays(1);
建立多值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);
讀取多值Cookie
HttpCookie aCookie = Request.Cookies["userInfo"]; string userName=aCookie.Values[“userName”]; string lastVisit=aCookie.Values[“lastVisit”];
修改和刪除Cookie
不能直接修改或刪除Cookie,只能建立一個新的Cookie,發送到用戶端以實現修改或刪除Cookie.
轉帖地址:http://dev.firnow.com/course/4_webprogram/asp.net/asp_netshl/2008430/112167.html