Search code examples
c#asp.netcookieshttpcontexthttpcookie

Why cookie is being deleted


I have an Asp.Net website, and have 2 cookies.

I create these cookies by this code;

public static void CreateCookie(string Cookie)
{
  HttpCookie cookie = new HttpCookie(Cookie);
  cookie.Expires = DateTime.Now.AddYears(1);
  HttpContext.Current.Response.Cookies.Add(cookie);
}

CreateCookie("Cookie1");
CreateCookie("Cookie2");

So both cookies' lifetime is 1 year, as I see on Chrome.

But when I check 1 day later, I see that Cookie1 is automatically deleted,
although I check the cookies without entering the website and just checking on Chrome.

I cannot prevent this. Why this occures ?
And how can I fix this ?

Update :
This error happens only on my own website.
And I'm going to check this on another pc and another browser.


Solution

  • You do not set a value to the cookies. Adding a cookie without value will make the browser delete the cookie with the given name, if it exists.

    Use a value:

    public static void CreateCookie(string Cookie, string value)
    {
      HttpCookie cookie = new HttpCookie(Cookie, value);
      cookie.Expires = DateTime.Now.AddYears(1);
      HttpContext.Current.Response.Cookies.Add(cookie);
    }
    
    CreateCookie("Cookie1", "Hello");
    CreateCookie("Cookie2", "world");