ASP.NET WebApi 2.0 HttpResponseMessage cookie被清除

时间:2015-12-11 21:10:36

标签: c# asp.net asp.net-mvc asp.net-web-api

我有一个项目从MVC转移到WebApi 2.我不得不偶尔在webapi的响应上设置一个cookie,所以我写了一个扩展OkNegotiatedContestResult的类,

   public class OkWithCookiesResult<T> : OkNegotiatedContentResult<T>
    {
        IEnumerable<HttpCookie> cookies;

        public OkWithCookiesResult(T content, IEnumerable<HttpCookie> cookies, ApiController controller)
            : base(content, controller)
        {
            this.cookies = cookies;
            foreach(var cookie in cookies)
            {
                cookie.Domain = Request.RequestUri.Host == "localhost" ? null : Request.RequestUri.Host;
                cookie.HttpOnly = true;
                cookie.Path = "/";
            }
        }

        public override async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            HttpResponseMessage response = await base.ExecuteAsync(cancellationToken);

            response.Headers.AddCookies(cookies.Select(c => c.ToCookieHeaderValue()));

            return response;
        }     
    }

这是ToCookieHeaderValue方法,

    public static CookieHeaderValue ToCookieHeaderValue(this HttpCookie cookie) {
        CookieHeaderValue val = new CookieHeaderValue(cookie.Name, cookie.Value);
        val.Expires = cookie.Expires;
        val.Domain = cookie.Domain;
        val.HttpOnly = cookie.HttpOnly;
        val.Path = cookie.Path;
        val.Secure = cookie.Secure;
        return val;
    }

一些调试代码留在那里,但你得到了要点。我的问题是我在请求完成后清除了添加到标题中的cookie。我想出了这个,因为我订阅了Application_EndRequest事件,最后的响应只有一个cookie,.ASPXAUTH的空值。这是否来自MVC的一些FormsAuthentication事件?

0 个答案:

没有答案