Search code examples
asp.netasp.net-mvccookieshttpmodule

Changing a cookie doesn't affect it until the next Request - how to fix this?


I am familiar with Microsoft's "best practices" for handling the life-cycle of a cookie (as defined on MSDN), and am following these, but have found an odd scenario that I need to fix. I can't imagine I'm the first to experience this, so wanted to see what the community's take on this was.

By the way, one obvious fix for what I am about to describe would be to force a re-direct, but for reasons I won't go into, a 302 is not an option.

Okay, so I receive a WebRequest and in that I have a specific cookie. Depending on the flow, I need to "remove" this cookie. To do this, I set the Response Cookie's value to null and set its expiration date to sometime last year.

However, later on, a very separate part of the code attempts to re-read the cookie and - guess what - it finds the old value. Note: this is still part of the SAME web-request, we've not yet returned to the client.

When we return to the Client's browser, the cookie is duly removed.

One solution I have is that, at the very beginning of the web-request, I copy the Request cookies into a separate NameValueCollection.

  • Every time I update a cookie value, I update both the cookie in the Response.Cookies collection, and I update the value in my separate NameValueCollection.
  • Everytime I delete a cookie, I expire the cookie in the Response.Cookies collection, and I remove it from the NameValueCollection
  • Every time I add a new cookie, I add it to both the Response.Cookies collection and my NameValueCollection.
  • Whenever I want to read a cookie's value, I read it from my NameValueCollection.

Thoughts?

Thanks

Griff


Solution

  • I first check if the Resonse.Cookies.AnyKeys contains my Cookie Name. If it does, then I read from the Response cookies. If it doesn't then I read from the Request cookies.