Send Cookie Using HTTP Response From Web API

Send cookie using HTTP response from Web API

This article shows how to send a cookie from the Web API to a client using a HTTP response. We all know that a cookie is a small file residing in the client's computer and stores data in plain text format. Whenever we make a HTTP request or response, we attach a cookie value with a HTTP message header.

The cookie may contain user's information and other necessary data. So, we can create a cookie in many ways and nearly every web programming language.

In this article we will see how to create and send a cookie from a Web API application. We know that the Web API is the latest service of Microsoft technology and we can host a RESTful service using it.

Anyway, there are several places to create and set cookies to HTTP request and response messages. We can set it at the action level.

So, whenever the action dispatches the response, it will set the cookie with a response message. Another place to set the cookie is within the request response pipeline of the Web API. We know that every request and response passes through the channel and whenever a response is passed, we can attach a cookie to the header part.

Anyway, this article explains how to set the cookie within the controller. Have a look at the following code.

So, create a Web API project and add a “SetCookecontroller” controller to it. The controller name is chosen by me, you are free to use any name.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Net.Http.Headers;  
  7. using System.Web.Http;  
  8. namespace MvcApplication2.Controllers  
  9. {  
  10.     public class SetCookieController : ApiController  
  11.     {  
  12.         public HttpResponseMessage Get()  
  13.         {  
  14.             var resp = new HttpResponseMessage();  
  15.             var cookie = new CookieHeaderValue("username""Sourav Kayal");  
  16.             cookie.Expires = DateTimeOffset.Now.AddDays(1);  
  17.             cookie.Domain = Request.RequestUri.Host;  
  18.             cookie.Path = "/";  
  19.             resp.Headers.AddCookies(new CookieHeaderValue[] { cookie });  
  20.             return resp;  
  21.         }  
  22.     }  
  23. } 

The example is very simple. At first we have created a HttpResponse message object and then we created an object of the ”CookieHeaderValue” class by passing a cookie name and it's value. We have set the expire data to the next data from the date of creation.

Then we set the domain to the current domain and the path to the root path. The last line is a very important one. In this line we are attaching a cookie to the HTTP response message. The point to note is that the Addcookie() function takes an array of cookies. Then we are happily returning the response message.

Now, we will run the application and check the HTTP response message in Fiddler.

Send cookie through HTTP response

In the header section of the HTTP message we are seeing that the cookie is set and the value is “Sourav kayal”, associated with the cookie value. We are getting the expiration date and time and domain with the path.

The main limitation of a cookie is it's numbers per domain. Since the number of cookies are limited it's a wise decision to insert more values into a single cookie. Those types of cookies are called multi-valued cookies.

Have a look at the following code. We have just modified our previous action.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Collections.Specialized;  
  4. using System.Linq;  
  5. using System.Net;  
  6. using System.Net.Http;  
  7. using System.Net.Http.Headers;  
  8. using System.Web.Http;  
  9. namespace MvcApplication2.Controllers  
  10. {  
  11.     public class SetCookieController : ApiController  
  12.     {  
  13.         public HttpResponseMessage Get()  
  14.         {  
  15.             var resp = new HttpResponseMessage();  
  16.             var nultiple = new NameValueCollection();  
  17.             nultiple["names"] = "Sourav";  
  18.             nultiple["surname"] = "Kayal";  
  19.             nultiple["age"] = "26";  
  20.             var cookie = new CookieHeaderValue("session", nultiple);  
  21.             resp.Headers.AddCookies(new CookieHeaderValue[] { cookie });  
  22.             return resp;  
  23.         }  
  24.     }  
  25. } 

The following is the output of the code above.

Send cookie through HTTP response

We see that multiple values has been set to the cookie separated by a “&” symbol that we can extract easily with a few lines of javascript or C# code.

Conclusion

Generally a cookie is used to store non-confidential data in the local disk. So, it's always a best practice not to store confidential data in a cookie.


Similar Articles