Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete cookie issue in C#

I'm trying to delete a cookie, however it doesn't get deleted. Here is the code I try to use.

if (Request.Cookies["dcart"] != null)
{
    Response.Write(Request.Cookies["dcart"].Expires);
    // Response 1/1/0001 12:00:00 AM

    Response.Write(Request.Cookies["dcart"].Value);
    // Response 229884

    HttpCookie myCookie = new HttpCookie("dcart");
    myCookie.Expires = DateTime.Now.AddDays(-1d);
    myCookie.Value = "";
    Response.Cookies.Add(myCookie);
}

Response.Write(Request.Cookies["dcart"].Expires);
// Response 1/1/0001 12:00:00 AM
Response.Write(Request.Cookies["dcart"].Value);
// Response 229884

When I retrieve the cookie again, nothing changes. I check w/ FireFox and Chrome same behavior. Interesting point is that expiration date shows correctly on the browsers but on the code.

I tried followings and didn't work.

  • Set expiration day to (tomorrow) and again set it for yesterday.
  • Restart the browser (happens different browsers and people)
  • Set the value something
  • Use HttpContext.Current.Request.Cookies["dcart"]....
  • Request.Cookies["dcart"].Expires = DateTime.Now.AddYears(-10);

PS. The code won't work directly on your machine, because you don't have the cookie.

like image 716
asr Avatar asked Dec 06 '12 23:12

asr


1 Answers

SOLVED

Problem was the path. The cookie I request was under "/store" path and the one I response path information to "/".

if (Request.Cookies["dcart"] != null)
{
   HttpCookie myCookie = new HttpCookie("dcart");
   myCookie.Expires = DateTime.Now.AddDays(-1d);
   myCookie.Path = "/store";
   Response.Cookies.Add(myCookie);
}

When I added path information, it's deleted.

Note: I used Firebug to trace the cookie path.

like image 85
asr Avatar answered Nov 13 '22 20:11

asr