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.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Net.Http;

using System.Net.Http.Headers;

using System.Web.Http;

 

namespace MvcApplication2.Controllers

{

    public class SetCookieController : ApiController

    {

        public HttpResponseMessage Get()

        {

            var resp = new HttpResponseMessage();

            var cookie = new CookieHeaderValue("username""Sourav Kayal");

            cookie.Expires = DateTimeOffset.Now.AddDays(1);

            cookie.Domain = Request.RequestUri.Host;

            cookie.Path = "/";

 

            resp.Headers.AddCookies(new CookieHeaderValue[] { cookie });

            return resp;

        }

    }

}

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 expire 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.

using System;

using System.Collections.Generic;

using System.Collections.Specialized;

using System.Linq;

using System.Net;

using System.Net.Http;

using System.Net.Http.Headers;

using System.Web.Http;

 

namespace MvcApplication2.Controllers

{

    public class SetCookieController : ApiController

    {

        public HttpResponseMessage Get()

        {

            var resp = new HttpResponseMessage();

            var nultiple = new NameValueCollection();

            nultiple["names"] = "Sourav";

            nultiple["surname"] = "Kayal";

            nultiple["age"] = "26";

            var cookie = new CookieHeaderValue("session", nultiple);

            resp.Headers.AddCookies(new CookieHeaderValue[] { cookie });

            return resp;

        }

    }

}

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 JavaScrpt 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.

Up Next
    Ebook Download
    View all
    Learn
    View all