Unable to update cookie in ASP.NET

后端 未结 1 836
醉梦人生
醉梦人生 2021-02-13 23:10

I\'m going nuts over this. I can write to a cookie, and then read it again. But at some point, i want to update the value it holds. Whenever i get the cookie again, i get the in

相关标签:
1条回答
  • 2021-02-13 23:48

    Try like this:

    var response = HttpContext.Current.Response;
    response.Cookies.Remove("UserSettings");
    response.Cookies.Add(cookie);
    

    But I suspect that your actual problem is that you are calling the WriteCookie method and the GetUserSettings method in the same HTTP request which doesn't work as you might think it would or as you might expect it to.

    The WriteCookie writes the cookie to Response so that it is available on subsequent requests but the GetUserSettings reads the cookie from the Request so you are getting the value of the cookie that was initially set when this request was initiated which of course is the old value. So after calling the WriteCookie to update the value of the user settings cookie, perform a redirect and only on the subsequent request use the GetUserSettings method.

    Also in ASP.NET MVC you typically don't want to use the static HttpContext.Current object but use the abstractions that this framework provides to you. I know you wrote those 2 methods as static but you should have written them as an extension method to the HttpContextBase object for example. This way you could have called them anywhere where you had an instance of this abstract base class which ASP.NET MVC provides you in many common places during the lifetime of an HTTP request.

    0 讨论(0)
提交回复
热议问题