我想在web api中创建一个演示登录服务,需要在响应上设置一个cookie。我怎么做?或者有更好的授权方式吗?
答案 0 :(得分:24)
添加对System.Net.Http.Formatting.dll
的引用,并使用AddCookies
类中定义的HttpResponseHeadersExtensions
扩展方法。
以下是a blog post describing this approach和MSDN topic。
如果那个程序集不适合你,那么这是我之前的答案:
旧答案如下
我更喜欢一种保持在HttpResponseMessage
范围内的方法,而不会渗透到HttpContext中,而HttpContext不是单元可测试的,并且根据主机不一定适用:
/// <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:
HttpResponseMessage response;
response.Headers.SetCookie(new Cookie("name", "value"));
答案 1 :(得分:7)
您可以将cookie添加到HttpContext.Current.Response.Cookies集合中。
var cookie = new HttpCookie("MyCookie", DateTime.Now.ToLongTimeString());
HttpContext.Current.Response.Cookies.Add(cookie);