ASP.NET: Cookies, value not being reset, cookie not being removed
I have a cookie called "g" with values "y" or "n"
I set it like this:
Response.Cookies("g").Value = "y"
Response.Cookies("g").Expires = DateTime.Now.AddHours(1)
I change it like this:
Request.Cookies("g").Value = "n"
and I try to destroy it like this
Response.Cookies("g").Expires = DateTime.Now.AddHours(-1)
The cookie gets set 开发者_StackOverflowfine, but I cannot change its value or destroy it
Thanks!
Try deleting it this way:
if (Request.Cookies["g"] != null)
{
HttpCookie myCookie = new HttpCookie("g");
myCookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(myCookie);
}
I think if you try creating the cookie and adding it to the Response like this it should work.
You want to add in a new cookie to the response that has the same name. Also I recommend going back a day and not just an hour.
To change the value of the cookie do this:
if (Request.Cookies["g"] != null)
{
HttpCookie myCookie = new HttpCookie("g");
myCookie.Expires = DateTime.Now.AddHours(1);
myCookie.Value = "n";
Response.Cookies.Add(myCookie);
}
The important thing to note with these examples is that we are observing the read-only request collection to see what is already in there, and then we are making changes or deleting by adding a new cookie to replace the one that was there before.
You cannot change the Request cookie, you can only "re-set" it in your response. Hence, you need to set the same cookie in your Response.
However the Expire-trick should work, but sometimes the DST (daylight saving time) might confuse the browser. Have you tried using a very old DateTime (like, 1970) in order to expire the cookie?
精彩评论