Introduction
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 www.c-sharpcorner.com, 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 www.c-sharpcorner.com 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.
Example:
Set-Cookie: seeeion-Id=123
Now an example with an attribute:
Set-Cookie: session-Id=123; Expires=12/12/2012;domain= Example.com; 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 "Example.com" then the cookie returned by the client to the subdomain of the "Example.com".
- 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:
- public HttpResponseMessage Get()
- {
- var response = new HttpResponseMessage();
- var Coki = new CookieHeaderValue("session-Id", "123");
- Coki.Expires = DateTimeOffset.Now.AddDays(2);
- Coki.Domain = Request.RequestUri.Host;
- Coki.Path = "/";
- response.Headers.AddCookies(new CookieHeaderValue[] { Coki });
- return response;
- }
We notice that the AddCookie takes an array of CookieHeaderValue instances:
- string ses_Id = "";
- CookieHeaderValue cookie = Request.Headers.GetCookies("session-Id").FirstOrDefault();
- if (Coki != null)
- {
- ses_Id = Coki["session-Iid"].Value;
- }
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.
Example:
- var response = new HttpResponseMessage();
- var value = new NameValueCollection();
- value["sid"] = "123";
- value["token"] = "hij";
- value["theme"] = "green";
- var Coki = new CookieHeaderValue("session", value);
- 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.
- string ses_Id = "";
- string ses_Token = "";
- string thm = "";
- CookieHeaderValue Coki = Request.Headers.GetCookies("session").FirstOrDefault();
- if (Coki != null)
- {
- CookieState cookie_State = Coki["session"];
- sessionId = cookie_State["sid"];
- sessionToken = cookie_State["token"];
- theme = cookie_State["theme"];
- }