我想在关闭浏览器时保留会话cookie。
这是我的cookie会话配置部分:
<authentication mode="Forms">
<forms name=".ASPXFORMSAUTH" cookieless="AutoDetect" defaultUrl="~/Default.aspx" loginUrl="~/Account/Login.aspx" timeout="99999999" />
</authentication>
我使用Chrome进行测试,但没关系,但是当我关闭浏览器时,Firefox和IE会删除cookie。
谢谢。
答案 0 :(得分:0)
按照设计,ASP.NET会话状态使用非持久会话cookie,这些cookie在您关闭浏览器时无法生存。
您需要一种使ASP.NET会话cookie持久化的方法。
创建持久性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);
阅读持久性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.
}