5.5 HTTP cookies in ASP. NET Web APIs
5.5 HTTP cookies in ASP. NET Web APIs
This article cited from: http://www.asp.net/web-api/overview/working-with-http/http-cookies
By Mike Wasson | September 17,201 2
Author: Mike Wasson | Date:
This topic describes how to send and receive HTTP cookies in web API.
This topic describes how to send and receive HTTP cookies in Web APIs.
Background on HTTP cookies
HTTP cookie background
This section gives a brief overview of how cookies are implemented at the HTTP level. For details, consult RFC 6265.
This section describes how to implement cookies at the HTTP level. For more information, see RFC 6265.
A cookie is a piece of data that a server sends in the HTTP response. the client (optionally) stores the cookie and returns it on subsequet requests. this allows the client and server to share state. to set a cookie, the server has des a set-Cookie header in the response. the format of a cookie is a name-value pair, with optional attributes. for example:
Cookie is a data segment sent by the server in the HTTP response. The client stores this cookie (optional) and returns it in subsequent requests. This allows the client and server to share the status. To set a cookie, the server must include a set-Cookie header in the response. The cookie format is a "name-value" pair with optional attributes. For example:
Set-COOKIE: Session-id = 1234567
Here is an example with attributes:
The following is an example with attributes:
Set-COOKIE: Session-id = 1234567; max-age = 86400; domain = example.com; Path = /;
To return a cookie to the server, the client has des a cookie header in later requests.
To return a cookie to the server, the client must contain a cookie header in subsequent requests.
COOKIE: session ID = 1234567
An HTTP response can include multiple set-Cookie headers.
An HTTP response can contain multiple set-Cookie headers.
Set-COOKIE: Session-Token = abcdef; Set-COOKIE: Session-id = 1234567;
The client returns multiple cookies using a single cookie header.
The client returns multiple cookies with a single cookie header.
COOKIE: Session-id = 1234567; Session-Token = abcdef;
The scope and duration of a cookie are controlled by following attributes in the Set-Cookie header:
The cookie range and duration are subject to the following attributes of the Set-Cookie header:
-
- Domain: Tells the client which domain shold receive the cookie. for example, if the domain is "example.com", the client returns the cookie to every subdomain of example.com. if not specified, the domain is the origin server.
Domain(Primary domain, or abbreviatedDomain): Tell the client which domain should receive the cookie. For example, if the domain is "example.com", the client will return the cookie to each subdomain of example.com. If not specified, this domain is the original server.
- Path: Restricts the cookie to the specified path within the domain. If not specified, the path of the request URI is used.
Path(PATH): restrict the cookie to a specific path of the primary domain. If not specified, the request URI path is used.
-
- Expires: Sets an expiration date for the cookie. The client deletes the cookie when it expires.
Expires(Expiration): Set the cookie expiration date. When the cookie expires, the client deletes the cookie.
-
- Max-age: Sets the maximum age for the cookie. The client deletes the cookie when it reaches the maximum age.
Max-age(Maximum age): set the maximum age of the cookie. When the cookie reaches the maximum age, the client deletes the cookie.
If both expires and max-age are set, Max-age takes precedence. if neither is set, the client deletes the cookie when the current session ends. (the exact meaning of "session" is determined by the User-Agent .)
If both expires and max-age are set, Max-age takes precedence. If no cookie is set, the client deletes the cookie at the end of the current session. (The exact meaning of "session" is determined by the user agent .)
However, be aware that clients may ignore cookies. for example, a user might disable cookies for privacy reasons. clients may delete cookies before they expire, or limit the number of Cookies stored. for privacy reasons, clients often reject "third party" cookies, where the domain does not match the origin server. in short, the server shocould not rely on getting back the cookies that it sets.
However, be aware that the client may ignore cookies. For example, a user may disable cookies for private reasons. The client may delete cookies before they expire, or limit the number of cookies to be saved. For private reasons, the client usually rejects "third-party" cookies that do not match the source server domain. In short, the server should not be dependent on the cookies it sets.
Cookies in Web APIs
Cookies in Web APIs
To add a cookie to an HTTP response, create a cookieheadervalue instance that represents the cookie. then call the addcookies extension method, which is defined in the system. net. HTTP. httpresponseheadersextensions class, to add the cookie.
To add a cookie to an HTTP response, you need to create a cookieheadervalue instance that represents the cookie. Call the addcookies Extension Method (defined in the system. net. http. httpresponseheadersextensions class) to add a cookie.
For example, the following code adds a cookie within a controller action:
For exampleCodeA cookie is added to a controller action:
Public httpresponsemessage get () {var resp = new httpresponsemessage ();
VaR cookie = new cookieheadervalue ("session-ID", "12345"); cookie. expires = datetimeoffset. now. adddays (1); cookie. domain = request. requesturi. host; cookie. path = "/";
Resp. headers. addcookies (New cookieheadervalue [] {cookie}); Return resp ;}
Notice that addcookies takes an array of cookieheadervalue instances.
Note that addcookies use an array of cookieheadervalue instances.
To extract the cookies from a client request, call the getcookies method:
To extract the cookie requested by the client, call the getcookies method:
String sessionid = "";
Cookieheadervalue cookie = request. headers. getcookies ("session-ID"). firstordefault (); If (cookie! = NULL) {sessionid = cookie ["session-ID"]. value ;}
A cookieheadervalue contains a collection of cookiestate instances. Each cookiestate represents one cookie. Use the indexer method to get a cookiestate by name, as shown.
Cookieheadervalue contains a set of cookiestate instances. Each cookiestate indicates a cookie. You can use the indexer method (cookie ["session-ID"]-Translator's note in the last line of the above Code) to obtain the cookiestate represented by the name, as shown above.
Structured cookie data
Structured cookie data
Describrowsers limit how many cookies they will store-both the total number, and the number per domain. therefore, it can be useful to put structured data into a single cookie, instead of setting multiple cookies.
Many browsers limit the number of cookies they store-the total number of cookies and the number of cookies for each domain. Therefore, it may be useful to put structured data into one cookie instead of setting multiple cookies.
RFC 6265 does not define the structure of cookie data.
RFC 6265 does not define the cookie data structure.
Using the cookieheadervalue class, you can pass a list of name-value pairs for the cookie data. These name-value pairs are encoded as URL-encoded form data in the Set-Cookie header:
Using the cookieheadervalue class, you can pass a set of "name-value" pairs for cookie data. These "name-value" pairs are encoded in the form data encoded as a URL in the Set-Cookie header:
VaR resp = new httpresponsemessage ();
VaR NV = new namevaluecollection (); NV ["Sid"] = "12345"; NV ["token"] = "abcdef "; NV ["theme"] = "dark blue"; var cookie = new cookieheadervalue ("session", NV );
Resp. headers. addcookies (New cookieheadervalue [] {cookie });
The previous Code produces the following set-Cookie header:
The above code generates the following set-Cookie header:
Set-COOKIE: session = SID = 12345 & token = abcdef & theme = Dark + blue;
The cookiestate class provides an indexer method to read the sub-values from a cookie in the Request Message:
The cookiestate class provides an index method to read the sub-value (sub-values) of the cookie in the Request Message ):
String sessionid = ""; string sessiontoken = ""; string theme = "";
Cookieheadervalue cookie = request. headers. getcookies ("session"). firstordefault (); If (cookie! = NULL) {cookiestate = cookie ["session"];
Sessionid = cookiestate ["Sid"]; sessiontoken = cookiestate ["token"]; theme = cookiestate ["theme"];}
Example: Set and retrieve cookies in a message handler
Example: Set and receive cookies in a message processor
the previous examples showed how to use cookies from within a web API controller. another option is to use message handlers. message handlers are invoked earlier in the pipeline than controllers. A message handler can read cookies from the request before the request reaches the Controller, or add cookies to the response after the Controller generates the response.
the preceding example demonstrates how to use cook from the web API controller. IE. Another option is to use "message handler, also known as message processing Program -Translator's note )". The message processor calls must be earlier than the controller in the request pipeline. The message processor can read the cookie of the request before the request reaches the Controller, or add the cookie to the response after the Controller generates a response (as shown in ).
The following code shows a message handler for creating session IDs. the session ID is stored in a cookie. the handler checks the request for the session cookie. if the request does not include the cookie, the handler generates a new session ID. in either case, the handler stores the session ID in the httprequestmessage. properties property bag. it also adds the session cookie to the HTTP response.
The following code demonstrates a message processor that creates a session ID. Session ID is stored in a cookie. This processor checks the requested session cookie. If the request does not contain cookies, the processor generates a new session ID. In any case, the processor stores the session ID in the httprequestmessage. properties property package. It also adds the session cookie to the HTTP response.
This implementation does not validate that the session ID from the client was actually issued by the server. Don't use it as a form of authentication! The point of the example is to show HTTP cookie management.
If the client session ID is actually published by the server, this implementation will not verify it. Do not use it for authentication! The key in this example is to demonstrate how to manage HTTP cookies.
Using system; using system. LINQ; using system. net; using system. net. HTTP; using system. net. HTTP. headers; using system. threading; using system. threading. tasks; using system. web. HTTP;
Public class sessionidhandler: delegatinghandler {static Public String sessionidtoken = "session-ID ";
Async protected override task
Sendasync (httprequestmessage request, cancellationtoken) {string sessionid;
// Try to get the session ID from the request; otherwise create a new ID. // try to get the request session ID; otherwise, create a new ID var cookie = request. headers. getcookies (sessionidtoken ). firstordefault (); If (cookie = NULL) {sessionid = guid. newguid (). tostring ();} else {sessionid = cookie [sessionidtoken]. value; try {guid = guid. parse (sessionid);} catch (formatexception) {// bad session ID. create a new one. // inferior session ID, create a new sessionid = guid. newguid (). tostring ();}}
// Store the session ID in the request property bag. // store the session ID request. properties [sessionidtoken] = sessionid in the request property package;
// Continue processing the HTTP request. // continue to process the HTTP request httpresponsemessage response = await base. sendasync (request, cancellationtoken );
// Set the session ID as a cookie in the Response Message. // set the session ID to a cookie response in the Response Message. headers. addcookies (New cookieheadervalue [] {New cookieheadervalue (sessionidtoken, sessionid )});
Return response ;}}
A controller can get the session ID from the httprequestmessage. properties property bag.
The controller can obtain the session ID through the httprequestmessage. properties attribute package.
Public httpresponsemessage get () {string sessionid = request. properties [sessionidhandler. sessionidtoken] as string;
Return new httpresponsemessage () {content = new stringcontent ("your session ID =" + sessionid )};}
after reading this article, give recommended