[ASP. NET Web API tutorial] 5.5 HTTP Cookie and apicookie in ASP. NET Web API

Source: Internet
Author: User
Tags http cookie subdomain

[ASP. NET Web API tutorial] 5.5 HTTP Cookie and apicookie in ASP. NET Web API
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 example, the following code adds a Cookie 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 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 cookies from the Web API controller. Another option is to use the Message Handler, also known as the Message Handler-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 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 = 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, please giveRecommendation

Reference page:

Http://www.yuanjiaocheng.net/webapi/action-method-returntype.html

Http://www.yuanjiaocheng.net/webapi/web-api-reqresq-format.html

Http://www.yuanjiaocheng.net/webapi/media-formatter.html

Http://www.yuanjiaocheng.net/webapi/webapi-filters.html

Http://www.yuanjiaocheng.net/webapi/create-crud-api-1.html

It learning materials

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.