tony
tony

Reputation: 2392

asp.net, deleting a cookie

This isn't the same as answered elsewhere (afaik), I'm documenting my answer for my own future use, but I'd also be interested in knowing more

I've created a cookie on the client in javascript like so

document.cookie = "Navigating=true";

and I've tried removing it on the server by setting the expiry date with

string cookieName = "Navigating";               
Response.Cookies.Remove(cookieName);

HttpCookie myCookie = new HttpCookie(cookieName);
myCookie.Expires = DateTime.Now.AddDays(-2);
Response.Cookies.Add(myCookie);

It doesn't work, here's the network trace

enter image description here

Note the name is wrong, it's cookie11 (I've removed the other cookies from the screenshot, it was the 11th cookie)

So now I set the value of the cookie to be something

myCookie.Value = "true";

and try again, it still doesn't work, screenshot 2 enter image description here

The key is now right but the path is still wrong, so finally

        if (Request.Cookies[cookieName] != null)
        {
            //Response.Cookies.Remove(cookieName);

            HttpCookie myCookie = new HttpCookie(cookieName);
            myCookie.Expires = DateTime.Now.AddDays(-2);
            myCookie.Value = "true";
            myCookie.Path = "";
            Response.Cookies.Add(myCookie);
        }

and now the server removes the cookie correctly

enter image description here

This works, so there's no question, but I'd be interested in knowing why the javascript cookie doesn't have a path but the asp.net one does by default

Upvotes: 2

Views: 360

Answers (1)

Koby Douek
Koby Douek

Reputation: 16693

Javascript cookies are without path by default. As you wrote, this can cause mismatches when using ASP.NET with Javascript when handling cookies. By default, ASP.NET sets the cookie path as / (root). So - to ensure full compatability, when creating cookies via Javascript, you can set a path by simply using:

document.cookie="Navigating=true;path=/";

Upvotes: 1

Related Questions