locked
Cookies are lost when browser is closed RRS feed

  • Question

  • User-1621660945 posted

    Hello friends

    I am trying to setup cookies, but when I close browser and reopen it, then my cookies does not exist.

    heres are my code:

    protected void Page_Load(object sender, EventArgs e)

    {

    if (Request.Cookies["myInfo"] != null)

    {

    Response.Write(

    "Welcome back Mr." + Request.Cookies["myInfo"].Value.ToString());

    }

    }

    protected void Button1_Click(object sender, EventArgs e)

    {
    HttpCookie myCookie = new HttpCookie("myInfo");

    myCookie.Value = TextBox1.Text;

    myCookie.Expires.AddMonths(1);

    Response.Cookies.Add(myCookie);

    }

    I want to add one more thing here, When I set my Expiration time maximum value , like

    myCookie.Expires =DateTime.MaxValue;

    then it works perfact, but I want to know why its not working when I set Expiration time limit in days and months format.

    Please help me to solve this.

    Saturday, June 4, 2011 1:51 PM

Answers

  • User-158764254 posted

    The Expires property of a cookie defaults to DateTime.MinValue (00:00:00.0000000, January 1, 0001).  So adding 1 month to that still results in an expired cookie.

    If you want to set it to expire 1 month from today, then you can do it like this:

    myCookie.Expires = DateTime.Now.AddMonths(1);

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, June 4, 2011 2:04 PM

All replies

  • User-158764254 posted

    The Expires property of a cookie defaults to DateTime.MinValue (00:00:00.0000000, January 1, 0001).  So adding 1 month to that still results in an expired cookie.

    If you want to set it to expire 1 month from today, then you can do it like this:

    myCookie.Expires = DateTime.Now.AddMonths(1);

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, June 4, 2011 2:04 PM
  • User-1621660945 posted

    Thank you brother, you solved it.

    Saturday, June 4, 2011 10:59 PM