1

I want to keep my session cookie when I close the browser.

Here is my config section for cookie session :

<authentication mode="Forms">
  <forms name=".ASPXFORMSAUTH" cookieless="AutoDetect" defaultUrl="~/Default.aspx" loginUrl="~/Account/Login.aspx" timeout="99999999" />
</authentication>

I test with Chrome and it's ok but with Firefox and IE the cookie is deleted when I close the browser.

Thank you.

1 Answers1

0

By design, ASP.NET Session state uses non-persistent session cookies which do not survive when you close your browser.

You need a means of making the ASP.NET session cookie persistent.

Creating persistent cookie.

//create a cookie
HttpCookie myCookie = new HttpCookie("myCookie");

//Add key-values in the cookie
myCookie.Values.Add("userid", "USER_ID_HERE");

//set cookie expiry date-time. Made it to last for next 12 hours.
myCookie.Expires = DateTime.Now.AddHours(12);

//Most important, write the cookie to client.
Response.Cookies.Add(myCookie);

Reading the persistent cookie.

//Assuming user comes back after several hours. several < 12.
//Read the cookie from Request.
HttpCookie myCookie = Request.Cookies["myCookie"];
if (myCookie == null)
{
    //No cookie found or cookie expired.
    //Handle the situation here, Redirect the user or simply return;
}

//ok - cookie is found.
//Gracefully check if the cookie has the key-value as expected.
if (!string.IsNullOrEmpty(myCookie.Values["userid"]))
{
    string userId = myCookie.Values["userid"].ToString();
    //Yes userId is found. Mission accomplished.
}

This might be useful as well

Community
  • 1
  • 1
Andrew Reyes
  • 152
  • 8