我正在创建具有以下行的cookie:
HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
userid.Expires.AddYears(1);
Response.Cookies.Add(userid);
现在我怎么才能让它持久呢?
如果在关闭浏览器后再次访问同一页面,我将无法将其取回.
我正在创建具有以下行的cookie:
HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
userid.Expires.AddYears(1);
Response.Cookies.Add(userid);
现在我怎么才能让它持久呢?
如果在关闭浏览器后再次访问同一页面,我将无法将其取回.
这是你可以做到的.
Writing the persistent cookie.
//create a cookie
HttpCookie myCookie = new HttpCookie("myCookie");
//Add key-values in the cookie
myCookie.Values.Add("userid", objUser.id.ToString());
//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.
}