2

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

tony
  • 2,178
  • 2
  • 23
  • 40
  • For my own reference. I also tried creating a cookie in the onclick of a hyperlink, asp.net couldn't see it. When I added a path of '/' then it did. Previously I created the cookie via a button click followed by a page reload – tony Jun 08 '17 at 07:23

1 Answers1

1

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=/";
Koby Douek
  • 16,156
  • 19
  • 74
  • 103
  • Bit more info to save people googling, why would I want to set a path? – tony Jun 07 '17 at 13:17
  • Hi @tony, I elaborated my answer. Hope it makes things clearer. – Koby Douek Jun 07 '17 at 13:20
  • I was thinking more of something like this, but that'll do https://stackoverflow.com/questions/576535/cookie-path-and-its-accessibility-to-subfolder-pages – tony Jun 07 '17 at 13:22