Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set a response cookie on HttpReponseMessage?

I would like to create a demo login service in web api and need to set a cookie on the response. How do I do that? Or are there any better way to do authorization?

like image 705
Tomas Jansson Avatar asked Mar 20 '12 19:03

Tomas Jansson


People also ask

Can API response set-cookie?

To set a cookie in REST API response, get the Response reference and use it's cookie() method.

How do I get the response header cookie?

Just set the Set-Cookie header in the response from the server side code. The browser should save it automatically. As a developer, you may be able to inspect the value of the cookies using "Developer Tools". And the same cookie will be sent in subsequent requests to the same domain, until the cookie expires.

How do I set cookies in API?

set() The set() method of the cookies API sets a cookie containing the specified cookie data. This method is equivalent to issuing an HTTP Set-Cookie header during a request to a given URL.


1 Answers

Add a reference to System.Net.Http.Formatting.dll and use the AddCookies extension method defined in the HttpResponseHeadersExtensions class.

Here is a blog post describing this approach, and the MSDN topic.

If that assembly isn't an option for you, here's my older answer from before this was an option:

Older answer follows

I prefer an approach that stays within the realm of HttpResponseMessage without bleeding into the HttpContext which isn't as unit testable and does not always apply depending on the host:

/// <summary>
/// Adds a Set-Cookie HTTP header for the specified cookie.
/// WARNING: support for cookie properties is currently VERY LIMITED.
/// </summary>
internal static void SetCookie(this HttpResponseHeaders headers, Cookie cookie) {
    Requires.NotNull(headers, "headers");
    Requires.NotNull(cookie, "cookie");

    var cookieBuilder = new StringBuilder(HttpUtility.UrlEncode(cookie.Name) + "=" + HttpUtility.UrlEncode(cookie.Value));
    if (cookie.HttpOnly) {
        cookieBuilder.Append("; HttpOnly");
    }

    if (cookie.Secure) {
        cookieBuilder.Append("; Secure");
    }

    headers.Add("Set-Cookie", cookieBuilder.ToString());
}

Then you can include a cookie in the response like this:

HttpResponseMessage response;
response.Headers.SetCookie(new Cookie("name", "value"));
like image 149
Andrew Arnott Avatar answered Sep 26 '22 10:09

Andrew Arnott