ASP.NET MVC cookie重复

时间:2015-07-08 10:05:18

标签: asp.net asp.net-mvc cookies

当我在响应中添加cookie时,请求获得两个重复的cookie。这是代码:

    HttpCookie cookie = Request.Cookies[Constants.CART_COOKIE_KEY]; // 1 "cart" coookie received from a client browser.
    if (cookie != null)
    {
        Request.Cookies.Remove(Constants.CART_COOKIE_KEY); //remove it. Now there is no cookie in the Request
        cookie.Expires = DateTime.Now.AddYears(2);
        cookie.Value = "test";
       //Response is empty until now
        Response.Cookies.Set(cookie); // add to the Response, but now there are even two "cart" cookies in the Request. WTF?
    }

对于我来说,拥有协调的值非常重要,因为我仍然需要在剩余的过程中使用Request中的值。但是当我向Response添加修改后的值时,Request会变得非常混乱。

1 个答案:

答案 0 :(得分:0)

您正在从请求中删除cookie并在响应中添加一个新cookie,该响应知道请求的状态...

我建议您使用OwinMiddleware来修改响应Cookie,因为您还在使用兼容的堆栈吗?

很容易插入请求的正确阶段。

public class CartCookieMiddleware : OwinMiddleware
{
    public CartCookieMiddleware(OwinMiddleware next) : base(next)
    {

    }

    /// <summary>
    /// Process an individual request.
    /// </summary>
    /// <param name="context"/>
    /// <returns/>
    public override async Task Invoke(IOwinContext context)
    {

        // Register an event when response headers are sent
        context.Response.OnSendingHeaders(state =>
        {
            // Get response from state
            var resp = (IOwinResponse)state;
            // Get request from state
            var req = resp.Context.Request;

            var cookie = req.Cookies.FirstOrDefault(c => c.Key.Equals(Constants.CART_COOKIE_KEY, StringComparison.OrdinalIgnoreCase)).Value;

            if (cookie != null)
            {
                resp.Cookies.Delete(Constants.CART_COOKIE_KEY);
            }
            else
            {
                cookie = "test";
            }

            resp.Cookies.Append(Constants.CART_COOKIE_KEY, cookie, new CookieOptions { HttpOnly = true, Secure = req.IsSecure });

        }, context.Response);

        await Next.Invoke(context);
    }
}
相关问题