如何设置上的Htt preponseMessage回应饼干吗? [英] How do I set a response cookie on HttpReponseMessage?
问题描述
我想创建的Web API演示登录服务,并需要设置响应的cookie。我怎么做?还是有什么更好的方法做授权?
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?
推荐答案
添加到 System.Net.Http.Formatting.dll
参考,并使用<$ C $在的Htt presponseHeadersExtensions
类中定义的C> AddCookies 扩展方法。
Add a reference to System.Net.Http.Formatting.dll
and use the AddCookies
extension method defined in the HttpResponseHeadersExtensions
class.
下面是一个博客文章描述这种方法和 MSDN主题一>
如果该程序集是不是一个选择,这是我的旧的答案在此之前的是一个选项:
If that assembly isn't an option for you, here's my older answer from before this was an option:
旧的答案如下
我preFER 的Htt presponseMessage
的领域内保持无出血到的HttpContext其中,一个方法不如单元测试和并不总是根据宿主应用:
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());
}
然后,可在这样的反应的cookie:
Then you can include a cookie in the response like this:
HttpResponseMessage response;
response.Headers.SetCookie(new Cookie("name", "value"));
这篇关于如何设置上的Htt preponseMessage回应饼干吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!