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 receives 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 specify then it uses the URI path.

Expires: It specifies the date/time when the cookie will be expire, 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:

        public HttpResponseMessage Get()

        {

            HttpResponseMessage respMessage = new HttpResponseMessage();

            respMessage.Content = new ObjectContent<string[]>(new string[] { "value1""value2" }, new JsonMediaTypeFormatter());

            CookieHeaderValue cookie = new CookieHeaderValue("session-id""123");

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

            cookie.Domain = Request.RequestUri.Host;

            cookie.Path = "/";

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

            return respMessage;

        }

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

   CookieHeaderValue cookie = new CookieHeaderValue("session-id""123"); This line of code displays the session id defined here, "123",

 cookie.Expires = DateTimeOffset.Now.AddDays(2); It displays the number of days then the cookie will expire.

  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:

public HttpResponseMessage Get()

        {

            HttpResponseMessage respMessage = new HttpResponseMessage();

            respMessage.Content = new ObjectContent<string[]>(new string[] { "value1""value2" }, new JsonMediaTypeFormatter());

            var se = new NameValueCollection();

            se["sessid"] = "123";

            se["3dstyle"] = "flat";

            se["theme"] = "Blue";

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

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

            cookie.Domain = Request.RequestUri.Host;

            cookie.Path = "/";

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

            return respMessage;

        }

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:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net.Http;

using System.Net.Http.Headers;

using System.Web;

 

namespace HTTPCokies.Handlers

{

    public class RequestStampCookieHandler:DelegatingHandler

    {

         static public string CookieStampToken = "cookie-stamp";      

        protected async override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(

         HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)

        {

            string cookie_stamp;

            var cookie = request.Headers.GetCookies(CookieStampToken).FirstOrDefault();

            if (cookie == null)

            {

                cookie_stamp = "COOKIE_STAMPER_" + Guid.NewGuid().ToString();

            }

            else

            {

                cookie_stamp = cookie[CookieStampToken].Value;

                try

                {

                    Guid guid = Guid.Parse(cookie_stamp.Substring(22));

                }

                catch (FormatException)

                {

                    // Invalid Stamp! Create a new one.

                    cookie_stamp = "COOKIE_STAMPER_" + Guid.NewGuid().ToString();

                }

            }

            request.Properties[CookieStampToken] = cookie_stamp;

            HttpResponseMessage response = await base.SendAsync(request, cancellationToken);

            response.Headers.AddCookies(new CookieHeaderValue[] {

               new CookieHeaderValue(CookieStampToken,cookie_stamp) 

              });

            return response;

        }

    }

}

   

Now we perform some changes in the "WebApiConfig.cs" file. In this file we add the following line:

   config.MessageHandlers.Add(new RequestStampCookieHandler());

 

Now execute the application; the output will be as:

 

Display one value of handler

Up Next
    Ebook Download
    View all
    Learn
    View all