Why is the cookie expiration date not surviving across sessions in ASP.NET?

后端 未结 1 1607
春和景丽
春和景丽 2021-01-05 15:51

I made some changes to the testbed page, so I could make my question clearer here.

The page has three buttons: Set; Clear; and Get.

Set ha

相关标签:
1条回答
  • 2021-01-05 16:34

    The Short Answer - You cannot read the cookie's expiration date and time.

    Slightly Longer Answer - This is not an issue of sessions in ASP.NET. It is an issue of what you can read from a cookie server-side in ASP.NET. Per the MSDN:

    The browser is responsible for managing cookies, and the cookie's expiration time and date help the browser manage its store of cookies. Therefore, although you can read the name and value of a cookie, you cannot read the cookie's expiration date and time. When the browser sends cookie information to the server, the browser does not include the expiration information. (The cookie's Expires property always returns a date-time value of zero.)

    You can read the Expires property of a cookie that you have set in the HttpResponse object, before the cookie has been sent to the browser. However, you cannot get the expiration back in the HttpRequest object.

    So basically, the cookie expiration date is set correctly. This can be verified by inspecting the cookie in the browser. Unfortunately, reading this cookie like in your Get function will return 1/1/0001.

    If you really want to get the expiration, then you'd have to store it in the cookie itself:

    Set

    DateTime exp = DateTime.Now.AddDays(1);
    HttpCookie PreferredCookie = new HttpCookie("PreferredCookie");
    PreferredCookie.Values.Add("cookieType", "Zref");
    PreferredCookie.Values.Add("exp", exp.ToString());
    PreferredCookie.Expires = exp;
    Response.Cookies.Set(PreferredCookie);
    

    Get

    HttpCookie PreferredCookie = Request.Cookies["PreferredCookie"];
    if (PreferredCookie != null)
    {
        CookieLiteral.Text = "Value = " + PreferredCookie["cookieType"] + "<br>";
        CookieLiteral.Text += "Expires = " + PreferredCookie["exp"];
    }
    else
    {
        CookieLiteral.Text = "No Cookie";
    }
    
    0 讨论(0)
提交回复
热议问题