2012-03-20 73 views
15

我想在web api中创建一个演示登录服务,并且需要在响应中设置一个cookie。我怎么做?或者有没有更好的方法来进行授权?如何在HttpReponseMessage上设置响应cookie?

+0

它看起来不像你可以在HttpResponseMessage上设置cookie。看看这个线程,也许它会帮助http://stackoverflow.com/questions/5463431/setting-cookies-within-a-wcf-service – 2012-03-20 19:37:15

回答

22

添加参考System.Net.Http.Formatting.dll,并使用在HttpResponseHeadersExtensions类中定义的AddCookies扩展方法。

这里是a blog post describing this approachMSDN topic

如果该程序集是不适合你的选择,这是我从在此之前旧的答案是选项:

年长的答案如下

我喜欢的HttpResponseMessage领域内保持这种做法无出血到这是不一样单元测试,并根据宿主并不总是适用的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")); 
+0

我同意,这看起来像一个更好的选择。更改了接受的答案,以指导用户未来。 – 2013-01-14 06:49:57

+0

这可能不再是答案吗?我发现这个DLL的唯一方法是通过Nuget,它明确指出它是为WebApi.Client高于2.0,低于2.1,所以这个答案是WebApi 2.我们现在与ASP.NET 4和I无法找到这个dll了。 – 2013-09-24 14:28:44

+0

@IsaacLlopis我想他们把它从扩展DLL移到了核心。 – 2014-06-12 20:10:38

6

您可以将Cookie添加到HttpContext.Current.Response.Cookies集合。

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

谢谢,正是我想要的,应该想到我自己。但实际上预计可以通过'HttpResponseMessage'获得。 – 2012-03-20 20:08:34

+0

这是我的第一个猜测,但由于某种原因,它不是。对于测试能力来说,这肯定会更好。 – Maurice 2012-03-20 20:13:54

+21

这个答案违背了WebAPI的使用方式。您不应该从WebAPI引用HttpContext.Current,因为如果您是自主主机,则它不会存在。测试位缺少像这样的辅助工具的负载。 RC将AddCookies()扩展方法添加到您应该使用的HttpResponseMessage.Headers中。 – Andrew 2012-07-09 09:04:16