HTTP Cookies in ASP.Net Web API


In this article, you will learn about cookies in the ASP. NET Web API. Cookies are used for storing the user-specific information. For example, if a user visits a site then we use the cookie for storing the preference or other information. And when the user visits the same site again then it find the information that was stored earlier.

What are the cookies

We can say that a cookie is a small text of information stored when the user visits the site. It retrieves the information of the user each time the same site is visited. Requests and pages correspond as they go between the Web server and browser.

Let's see an example in which the user sends a request for a page from the site, the application does not only send the page but also it sends a cookie that contains the date and time. And when the browser gets the page it also gets a cookie that is stored on the user's hard disk.

Again the user requests the page from the same site. When the user enters the URL then the browser reads the cookie from the hard disk associated with the URL. If the cookie exists then the browser sends the cookie with the page request. Now the application determines the date and time that the user last visited the site. We use the cookie to send the message to the user for checking the expiry of the cookie.

A cookie is not associated with a specific page, it is associated with the site. So the server and the browser exchange the cookie information, no matter what page the user requests from your site. Cookies are used for short purposes to help you remember the site.

HTTP cookies

We know that a cookie is a piece of information sent by the server as the HTTP response. It is optional for the client to store the cookie and return it in subsequent requests. It allows the client and server to share the state. There is a need for including the Set-Cookie Header in a response for setting the cookie. There is the format of name-value pair with optional attribute.


Set-Cookie: seeeion-Id=123

Now an example with an attribute:

Set-Cookie: session-Id=123; Expires=12/12/2012;domain=; path=/;

We use the cookie Header in the later request for returning the cookie to the client:

Cookie: session-Id=123;


HTTP response that includes multiple sets of cookie headers:

Set-Cookie: session-token=hij;

Set-Cookie: session-Id=123;

By using the single cookie the client returns multiple cookies:

Cookie: session-Id=123;session-token=hij;

The following are the attributes used for controlling the scope and duration:

  • Domain:
    It defines which domain receives the cookie. For example if there is the domain "" then the cookie returned by the client to the subdomain of the "".
  • Path:
    It restricts the cookie within the specified path.
  • Expires:
    It sets the expiry date of the cookie after this date the cookie can be  removed by the client.
  • Max-Age:
    It sets the maximum age of an cookie. After reaching this date the cookie can be removed by the client.

If we defined both Max-Age and Expires then the Max-Age takes the higher preference. If there is no one defined then the cookie is deleted by the client after completing the current session.

Cookies in Web API

We create the instance of the "CookisHeaderValue" class for adding the cookie to an HTTP response that represents the cookie. Now we call the "AddCookie"extension method. This method exists in the "System.Net.Http.HttpResponseHeaderExtensions" class.

Example of add the cookie in the controller:

  1. public HttpResponseMessage Get()  
  2. {  
  3.     var response = new HttpResponseMessage();  
  4.     var Coki = new CookieHeaderValue("session-Id""123");  
  5.     Coki.Expires = DateTimeOffset.Now.AddDays(2);  
  6.     Coki.Domain = Request.RequestUri.Host;  
  7.     Coki.Path = "/";  
  8.     response.Headers.AddCookies(new CookieHeaderValue[] { Coki });  
  9.     return response;  
  10. } 

We notice that the AddCookie takes an array of CookieHeaderValue instances:

  1. string ses_Id = "";  
  2. CookieHeaderValue cookie = Request.Headers.GetCookies("session-Id").FirstOrDefault();  
  3. if (Coki != null)  
  4. {  
  5.     ses_Id = Coki["session-Iid"].Value;  
  6. } 

CookieHeaderValue is the collection of the instances of the CookieStates. And one cookie is represented by every CookieState.

Structured Cookie Data

There are many browsers that limit the storing of cookies that are the total number of cookies and the number of cookies as per domain.


  1. var response = new HttpResponseMessage();  
  2. var value = new NameValueCollection();  
  3. value["sid"] = "123";  
  4. value["token"] = "hij";  
  5. value["theme"] = "green";  
  6. var Coki = new CookieHeaderValue("session", value);  
  7. response.Headers.AddCookies(new CookieHeaderValue[] { Coki });   

There is the CookieState class given as an indexer method for reading the value from the cookie in the request message.

  1. string ses_Id = "";  
  2. string ses_Token = "";  
  3. string thm = "";  
  4. CookieHeaderValue Coki = Request.Headers.GetCookies("session").FirstOrDefault();  
  5. if (Coki != null)  
  6. {  
  7.     CookieState cookie_State = Coki["session"];  
  8.     sessionId = cookie_State["sid"];  
  9.     sessionToken = cookie_State["token"];  
  10.     theme = cookie_State["theme"];  
  11. }