How do I set a response cookie on HttpReponseMessage?

…衆ロ難τιáo~ 提交于 2020-01-12 06:31:25

问题


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?


回答1:


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"));



回答2:


You can add the cookie to the HttpContext.Current.Response.Cookies collection.

    var cookie = new HttpCookie("MyCookie", DateTime.Now.ToLongTimeString());
    HttpContext.Current.Response.Cookies.Add(cookie);


来源:https://stackoverflow.com/questions/9793591/how-do-i-set-a-response-cookie-on-httpreponsemessage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!