ASP.NET中cookie读写方法介绍

<div>Cookie (HttpCookie的实例)提供了一种在 Web 应用程序中存储用户特定信息的方法。例如,当用户访问您的站点时,您可以使用Cookie 存储用户首选项或其他信息。当该用户再次访问您的网站时,应用程序便可以检索以前存储的信息。</div>
<div></div>
<div>ASP.NET中的cookie:创建Cookie方法 (1)</div>
<div></div>
<div>Response.Cookies[“userName”].Value = “admin”;</div>
<div></div>
<div>Response.Cookies[“userName”].Expires = DateTime.Now.AddDays(1);</div>
<div>//如果不设置失效时间,Cookie信息不会写到用户硬盘,浏览器关闭将会丢弃。</div>
<div>ASP.NET中的cookie:创建Cookie方法 (2)</div>
<div></div>
<div>HttpCookie aCookie = new HttpCookie(“lastVisit”);</div>
<div></div>
<div>//上一次访问时间</div>
<div></div>
<div>aCookie.Value = DateTime.Now.ToString();</div>
<div></div>
<div>aCookie.Expires = DateTime.Now.AddDays(1);</div>
<div></div>
<div>Response.Cookies.Add(aCookie);</div>
<div>ASP.NET中的cookie:访问Cookie方法(1)</div>
<div></div>
<div>if(Request.Cookies[“userName”] != null)</div>
<div></div>
<div>Label1.Text = Server.HtmlEncode(Request.Cookies[“userName”].Value);</div>
<div>访问Cookie方法(2)</div>
<div></div>
<div>if(Request.Cookies[“userName”] != null) {</div>
<div></div>
<div>HttpCookie aCookie = Request.Cookies[“userName”];</div>
<div></div>
<div>Label1.Text = Server.HtmlEncode(aCookie.Value);</div>
<div></div>
<div>}</div>
<div>ASP.NET中的cookie:创建多值Cookie方法 (1)</div>
<div></div>
<div>Response.Cookies[“userInfo”][“userName”] = “admin”;</div>
<div></div>
<div>Response.Cookies[“userInfo”][“lastVisit”] = DateTime.Now.ToString();</div>
<div></div>
<div>Response.Cookies[“userInfo”].Expires = DateTime.Now.AddDays(1);</div>
<div>ASP.NET中的cookie:创建多值Cookie方法 (2)</div>
<div></div>
<div>HttpCookie aCookie = new HttpCookie(“userInfo”);</div>
<div></div>
<div>aCookie.Values[“userName”] = “admin”;</div>
<div></div>
<div>aCookie.Values[“lastVisit”] = DateTime.Now.ToString();</div>
<div></div>
<div>aCookie.Expires = DateTime.Now.AddDays(1);</div>
<div></div>
<div>Response.Cookies.Add(aCookie);</div>
<div>ASP.NET中的cookie:读取多值Cookie</div>
<div></div>
<div>HttpCookie aCookie = Request.Cookies[“userInfo”];</div>
<div></div>
<div>string userName=aCookie.Values[“userName”];</div>
<div></div>
<div>string lastVisit=aCookie.Values[“lastVisit”];</div>
<div>ASP.NET中的cookie:修改和删除Cookie</div>
<div></div>
<div>不能直接修改或删除Cookie,只能创建一个新的Cookie,发送到客户端以实现修改或删除Cookie。</div>