0

The question is quite straightforward:

How to replace a HttpCookie in MVC3? (Assuming we have access to the HttpContext instance)

Cristian E.
  • 3,116
  • 7
  • 31
  • 61

1 Answers1

1

Use SetCookie

var cookie = Request.Cookies["cookieName"];
if (cookie != null)
{
    cookie.Value = "new value";
    Response.SetCookie(cookie);
}
James
  • 80,725
  • 18
  • 167
  • 237
  • I have a question. When calling `Response.Cookies.Remove("CookieName");` The clients browser still holds this cookie? I saw some examples with Expiration=DateTime.Now.AddDays(-1)... can you explain the effects of both please? – Cristian E. Jan 14 '14 at 15:07
  • @Christian yes, the server has no control over the client. All `Remove` does is make sure the cookie is not sent back with the request. The only way to make the browser delete the cookie is to expire it. – James Jan 14 '14 at 15:11
  • I'll do some testings if works, I'll mark it as an answer. Thank you! – Cristian E. Jan 14 '14 at 15:11
  • I did some tests, and the results are positive :). Hope there are no rocks under the water.. I'll mark it as an answer! Thank you very much for your help! – Cristian E. Jan 14 '14 at 15:23
  • @Christian you should be fine with this approach, it is the recommended way. – James Jan 14 '14 at 15:23