How To Set Cookies in ASP.Net Web API

Introduction

This article explains how to set cookies in the Web API. A cookie is used for sending information to the HTTP server in an HTTP response. Cookies store the user-specific information. For example, if a user visits a site then we use the cookie for storing the preference or other information.

A cookie is controlled by some attribute set in the cookie header, these attributes are as follows:

Domain: It is the specified domain that is receiving the cookie. If the domain is not specified then the domain is the origin server.

Path: It specifies the limit in the domain if the path is not specified then it uses the URI path.

Expires: It specifies the date/time when the cookie will be expired, the user can delete the cookie when it has expired.

Max-age: It is a numeric value that specifies the timespan of the cookie that includes the life of the cookie. It can be deleted if it reaches its maximum age like as "expires" does.

Web API and Cookies

We know that the Web API creates services over the HTTP. It can be a web page for making AJAX requests, it can be a native app for retrieving the data or it can be a headless bot for pooling the data. The Web API does the work over the HTTP and the cookie is the part of the HTTP.

Now we create the Web API application for setting the cookie.

Step 1

  • Start Visual Studio 2013.
  • From the Start window select "New Project" .
  • Select "Installed" -> "Template" -> "Visual Studio 2012" and then select "ASP.NET MVC4 Web Application".

    Select MVC4 application
  • Click on the "Ok" button.

    Select web API
  • From the "MVC4" project window select "Web API".

Step 2

Now we set the cookie in the Values Controller. We use the "HttpResponseMessage" for the Get request of the Web API. From the Solution Explorer select the Values controller from the Controller folder and add the following code:

  1. public HttpResponseMessage Get()  
  2. {  
  3.     HttpResponseMessage respMessage = new HttpResponseMessage();  
  4.     respMessage.Content = new ObjectContent<string[]>(new string[] { "value1""value2" }, new JsonMediaTypeFormatter());  
  5.     CookieHeaderValue cookie = new CookieHeaderValue("session-id""123");  
  6.     cookie.Expires = DateTimeOffset.Now.AddDays(2);  
  7.     cookie.Domain = Request.RequestUri.Host;  
  8.     cookie.Path = "/";  
  9.     respMessage.Headers.AddCookies(new CookieHeaderValue[] { cookie });  
  10.     return respMessage;  
  11. }

In this application we need to add the two namespaces "System.Net.Http.Header" for the "Cooki HeaderValue" and "System.Net.Http.Formatters" for the "JsonMediaTypeFormatter".

  1. CookieHeaderValue cookie = new CookieHeaderValue("session-id""123"); //This line of code displays the session id defined here, "123",  
  2. cookie.Expires = DateTimeOffset.Now.AddDays(2); //It displays the number of days then the cookie will expire.  
  3. cookie.Domain = Request.RequestUri.Host; //It specifies the domain by which the cookie is received.   

Now we execute the application, copy the URL and open the fiddler, click on the compose button and paste the URL and navigate to the URL with the "http://localhost:58290/api/values" and click on the "Ok" button. We can see the output like this:

Copy the URL

Display Cookies detail

Step 3

Now add the cookie with Multiple values, add the following code to the ValuesController:

  1. public HttpResponseMessage Get()  
  2. {  
  3.      HttpResponseMessage respMessage = new HttpResponseMessage();  
  4.      respMessage.Content = new ObjectContent<string[]>(new string[] { "value1""value2" }, new JsonMediaTypeFormatter());  
  5.      var se = new NameValueCollection();  
  6.      se["sessid"] = "123";  
  7.      se["3dstyle"] = "flat";  
  8.      se["theme"] = "Blue";  
  9.      var cookie = new CookieHeaderValue("session", se);  
  10.      cookie.Expires = DateTimeOffset.Now.AddDays(2);  
  11.      cookie.Domain = Request.RequestUri.Host;  
  12.      cookie.Path = "/";  
  13.      respMessage.Headers.AddCookies(new CookieHeaderValue[] { cookie });  
  14.      return respMessage;  
  15. } 

Now again execute the application with the same procedure:

Display Cookies detail

Step 4

Now we set the cookie in the Web API handler

For adding the cookie outside the controller we create the "DelegateHandler". The request go to the controller through the handler and response comes out through the handler.

We add a folder to the project named "Handlers" and in this folder add a class named "RequestStampCookieHandler".

Add the class

Add the following code to this class:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net.Http;  
  5. using System.Net.Http.Headers;  
  6. using System.Web;  
  7. namespace HTTPCokies.Handlers  
  8. {  
  9.     public class RequestStampCookieHandler:DelegatingHandler  
  10.     {  
  11.         static public string CookieStampToken = "cookie-stamp";        
  12.         protected async override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(  
  13.         HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)  
  14.         {  
  15.             string cookie_stamp;  
  16.             var cookie = request.Headers.GetCookies(CookieStampToken).FirstOrDefault();  
  17.             if (cookie == null)  
  18.             {  
  19.                 cookie_stamp = "COOKIE_STAMPER_" + Guid.NewGuid().ToString();  
  20.             }  
  21.             else  
  22.             {  
  23.                 cookie_stamp = cookie[CookieStampToken].Value;  
  24.                 try  
  25.                 {  
  26.                     Guid guid = Guid.Parse(cookie_stamp.Substring(22));  
  27.                 }  
  28.                 catch (FormatException)  
  29.                 {  
  30.                     // Invalid Stamp! Create a new one.  
  31.                     cookie_stamp = "COOKIE_STAMPER_" + Guid.NewGuid().ToString();  
  32.                 }  
  33.             }  
  34.             request.Properties[CookieStampToken] = cookie_stamp;  
  35.             HttpResponseMessage response = await base.SendAsync(request, cancellationToken);  
  36.             response.Headers.AddCookies(new CookieHeaderValue[] {  
  37.                new CookieHeaderValue(CookieStampToken,cookie_stamp)   
  38.               });  
  39.             return response;  
  40.         }  
  41.     }  
  42. }
Now we perform some changes in the "WebApiConfig.cs" file. In this file we add the following line:
  1. config.MessageHandlers.Add(new RequestStampCookieHandler());  
Now execute the application; the output will be as:

Display one value of handler