views:

30

answers:

2

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 fine, but I cannot change its value or destroy it

Thanks!

+1  A: 

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.

Brendan Enrick
thanks, that works well for setting the cookie, but not for destroying it
Notice that I am setting the expire date in the past. This will work for deleting the cookie.
Brendan Enrick
Oh Ok, that will work.
I am trying to reset value by doing this: if not request.cookies("g") is nothing then response.cookies("guest").value="n", but no luck
Won't this create a new cookie?
ok one moment, thanks for the help
No, by adding the same cookie again, we will in fact just be changing the cookie to be the new one. In the delete case that will mean it expires and in the change case it means the value will change.
Brendan Enrick
Great that works like charm now!
+1  A: 

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?

jishi