您的位置:首页 > 其它

状态管理之Cookie

2009-12-07 17:40 204 查看
一、Cookie工作流程
如果在用户请求站点中不仅仅是一个页面,还有一个包含过期时间的 Cookie,用户的浏览器在获得页面的同时还获得了该 Cookie,并将它存储在用户硬盘上的某个文件夹中。

以后,如果该用户再次请求该站点,浏览器便会在本地硬盘上查找与之关联Cookie。如果该 Cookie 存在,浏览器便将该 Cookie 与页请求一起发送到请求站点。

二、Cookie相关规则

浏览器负责管理用户系统上的 Cookie。Cookie 通过 HttpResponse 对象发送到浏览器,该对象公开称为 Cookies 的集合。可以将 HttpResponse 对象作为 Page 类的 Response 属性来访问。要发送给浏览器的所有 Cookie 都必须添加到此集合中。创建 Cookie 时,需要指定 Name 和 Value。每个 Cookie 必须有一个唯一的名称,以便以后从浏览器读取 Cookie 时可以识别它。由于 Cookie 按名称存储,因此用相同的名称命名两个 Cookie 会导致其中一个 Cookie 被覆盖。

三、Cookie操作

1:添加单值Cookie到Cookies集合中

Response.Cookies["userName"].Value = "patrick";

Response.Cookies["userName"].Expires = DateTime.Now.AddDays(1d);

HttpCookie aCookie = new HttpCookie("lastVisit");

aCookie.Value = DateTime.Now.ToString();

aCookie.Expires = DateTime.Now.AddDays(1d);

Response.Cookies.Add(aCookie);

2:添加多值Cookie到Cookies集合中

Response.Cookies["userInfo"]["userName"] = "patrick";

Response.Cookies["userInfo"]["lastVisit"] = DateTime.Now.ToString();

Response.Cookies["userInfo"].Expires = DateTime.Now.AddDays(1);

HttpCookie aCookie = new HttpCookie("userInfo");

aCookie.Values["userName"] = "patrick";

aCookie.Values["lastVisit"] = DateTime.Now.ToString();

aCookie.Expires = DateTime.Now.AddDays(1);

Response.Cookies.Add(aCookie);

3:读取单值Cookie值

if(Request.Cookies["userName"] != null)

Label1.Text = Server.HtmlEncode(Request.Cookies["userName"].Value);

if(Request.Cookies["userName"] != null)

{

HttpCookie aCookie = Request.Cookies["userName"];

Label1.Text = Server.HtmlEncode(aCookie.Value);

}

4:读取多值Cookie值

if(Request.Cookies["userInfo"] != null)

{

Label1.Text =

Server.HtmlEncode(Request.Cookies["userInfo"]["userName"]);

Label2.Text =

Server.HtmlEncode(Request.Cookies["userInfo"]["lastVisit"]);

}

5:删除cookie

if (Request.Cookies["UserSettings"] != null)

{

HttpCookie myCookie = new HttpCookie("UserSettings");

myCookie.Expires = DateTime.Now.AddDays(-1d);

Response.Cookies.Add(myCookie);

}

6、显示所有cookie

为什么HttpCookieCollection的Enumerator只对Key进行遍历,我想这主要是出于性能的考虑。返回一个Key比返回一个Cookie对象效率高。

你期望在对Cookies做遍历操作(Enumerate)时返回Cookie对象, 但Enumerator如果返回Cookie是需要做一个 new Cookie()操作,这意味着会来一个对象拷贝。有些Cookie对象是比较大, 拷贝效率非常低。

遍历Cookies可以这样:
foreach(string key in Request.Cookies)
{
Cookie cookie = Request.Cookies[key]; //没有产生新Cookie对象, 效率比较高。

// your code
} 回复 引用

又想了一下,发现HTTPCookieCollection可以通过索引访问,最好的遍历方法应该用for而不是foreach:

for(int i=0; i < Request.Cookies.Count; i++)
{
HttpCookie cookie = Request.Cookies[i];

//......
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: