Search code examples
asp.net-mvccookiesasp.net-web-apirequest-headers

Sending cookie from client to web api


In my client side (controller of MVC application) I am using the code below to set cookie value:

HttpCookie cookie = new HttpCookie("TestCookie");
cookie.value = 'Test';
HttpContext.Request.Cookies.Add(cookie);

I am also setting the cookie value in request header. This is done when I am configuring breeze entitymanager. I use breeze queries to get data from web api.

'Cookie': UserProfileID = config.getCookies('UserProfileID')

But in Web API, I always find that there are no cookies present in request header.

request.Headers.GetCookies("UserProfileID").FirstOrDefault()

Solution

  • To set a cookie, you need to add it to the Response object, not the Request.

    var cookie = new HttpCookie("TestCookie");
    cookie.Value = "Test";
    HttpContext.Response.Cookies.Add(cookie);
    

    Upon more research, I found this question. The answer provides some insight about the nature of Web API:

    There's not a whole lot to work with here, but generally speaking, Web API diverges from MVC mostly in that it's fully REST-compliant, whereas MVC is not. REST-compliant applications are stateless (in other words: no session, no cookies, etc.). Everything the API endpoint needs must be sent along with the request either in the URL, the request headers or the request body. That means you could send the value of the cookie (not the cookie, itself) in the query string of a GET request or the body of a POST, or as is typical with REST API auth, as an Authorization HTTP header.

    So to get your desired result, you would need to extract the value of the cookie on the client in your MVC application, then send it along as part of the data of your API request, or use an Authorization HTTP header as suggested.