在编写一个支持用户首选项的web page的时候,一个需要解决的问题就是将首选项保存到什么地方。 http是一种无状态的协议:当用户浏览一个站点的时候,Web Server看到的是从任意IP传来的一系列的http请求,这些请求可能与来自其他IP地址的请求混合。为了存储首选项,要么将他们存在服务器上,并把每个传入的http请求与存储的首选项关联起来,要么提出一种方法将用户首选项编码进各自的http请求中,而Cookie就是实现后者的一种简便机制。
- Cookie是在每次请求时从浏览器传递给Web服务器的数据块。cookie在http头----cookie头中传递。如:以下就是一个包含cookie的http请求:
GET /study1/MyQuotes/MyQuotes.aspx HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*
Accept-Language: zh-cn
UA-CPU: x86
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon; .NET CLR 1.1.4322)
Host: localhost
Connection: Keep-Alive
Cookie: MyQuotes=ShowQuotescookie有名称和值,上述cookie名称是MyQuotes,值是 ShowQuotes。浏览器可以在一个以分号分割的列表中一次传递多个cookie 如:Cookie: MyQuotes=ShowQuotes;FavourColor=Blue
- 很多Web站点用cookie来识别返回用户。cookie 有时包含用户首选项,有时可以携带用户验证信息,以避免用户重复登陆。ASP.NET将返回用户与Web服务器上存储的Session相关联。
- 当一个包含cookie的请求到达时候,服务器解析并解释该Cookie,因此它是与应用程序高度相关的
- 大多数浏览器都允许禁用cookie.有些站点会提示您如果cookie 不可用,它们将不能正常工作。这通常是因为他们使用cookie来登记用户的首选项,登陆信息或则其他类似信息。
- Cookie由于安全性的原因,声誉并不好,但基本上他们是无害的,只要我们不用它来保存一些敏感的信息。事实上,Cookie是非常有用的,它是无状态协议作为传递信息的重要手段
Cookie是怎么样创建的?浏览器怎么知道什么时候要发出Cookie,具体发出什么内容?答案就是:web服务器通过在Http响应的set-cookie头返回cookie来创建它。
Here are some sample exchanges which are designed to illustrate the use of cookies.
First Example transaction sequence:
-
Client requests a document, and receives in the response:
-
Set-Cookie: CUSTOMER=WILE_E_COYOTE; path=/; expires=Wednesday, 09-Nov-99 23:12:40 GMT
When client requests a URL in path "/" on this server, it sends:
-
Cookie: CUSTOMER=WILE_E_COYOTE
Client requests a document, and receives in the response:
-
Set-Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001; path=/
When client requests a URL in path "/" on this server, it sends:
-
Cookie: CUSTOMER=WILE_E_COYOTE; PART_NUMBER=ROCKET_LAUNCHER_0001
Client receives:
-
Set-Cookie: SHIPPING=FEDEX; path=/foo
When client requests a URL in path "/" on this server, it sends:
-
Cookie: CUSTOMER=WILE_E_COYOTE; PART_NUMBER=ROCKET_LAUNCHER_0001
When client requests a URL in path "/foo" on this server, it sends:
-
Cookie: CUSTOMER=WILE_E_COYOTE; PART_NUMBER=ROCKET_LAUNCHER_0001; SHIPPING=FEDEX
Second Example transaction sequence:
-
Assume all mappings from above have been cleared.
-
Set-Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001; path=/
When client requests a URL in path "/" on this server, it sends:
-
Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001
Client receives:
-
Set-Cookie: PART_NUMBER=RIDING_ROCKET_0023; path=/ammo
When client requests a URL in path "/ammo" on this server, it sends:
-
Cookie: PART_NUMBER=RIDING_ROCKET_0023; PART_NUMBER=ROCKET_LAUNCHER_0001
- NOTE: There are two name/value pairs named "PART_NUMBER" due to the inheritance of the "/" mapping in addition to the "/ammo" mapping.
Client receives: