Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cookie not updating

Tags:

c#

cookies

I am trying to update a cookie value, but it doesn't work - everything I have tried doesn't update the cookie and I always get the initial value of the cookie.

So I have searched and according to MSDN I should be able to update a cookie by doing the following:

HttpCookie cookie = new HttpCookie("cookiename");
cookie.Value = cookieValue;
cookie.Expires = DateTime.Now.AddDays(30);
HttpContext.Current.Response.Cookies.Set(cookie); // also just tried using .Add again here

As this didn't work, I did another search and people on SO said I should be able to do this:

HttpContext.Current.Response.Cookies["cookiename"].Value = cookieValue;
HttpContext.Current.Response.Cookies["cookiename"].Expires = DateTime.Now.AddDays(30);

But this didn't work either so I tried deleting the cookie and re-adding it:

HttpCookie cookie = new HttpCookie("cookiename");
cookie.Value = cookieValue;
cookie.Expires = DateTime.Now.AddDays(-1);
HttpContext.Current.Response.Cookies.Add(cookie);

cookie.Expires = DateTime.Now.AddDays(30);
HttpContext.Current.Response.Cookies.Add(cookie);

I have also tried removing the cookie with the following before re-adding it

ResponseCookies.Remove("cookiename");

And this also didn't work, so I'm now not sure what else to try. Does anyone know how to update a cookie with c#?

Update

If I step through the code and check HttpContext.Current.Request.Cookies["cookiename"].Value after I have updated it, it shows the new value. If I then recycle the app pool so that the cookie has to be read from the file again, it shows the original value, so it seems the above code is not updating the physical cookie

like image 402
Pete Avatar asked Oct 18 '22 13:10

Pete


1 Answers

You can't!

According to MSDN, you have replace the current cookie with a new one with the same name. There is a whole section about this.

Modifying and Deleting Cookies

You cannot directly modify a cookie. Instead, changing a cookie consists of creating a new cookie with new values and then sending the cookie to the browser to overwrite the old version on the client.


Update

After writing in the comments, we found the problem here.

You are also not allowed to use a semi-colon in your cookie-value, according to the specs.

This string is a sequence of characters excluding semi-colon, comma and white space. If there is a need to place such data in the name or value, some encoding method such as URL style %XX encoding is recommended, though no encoding is defined or required.

like image 70
Smartis Avatar answered Oct 27 '22 09:10

Smartis