如何在asp.net中创build持久性cookie?

我使用以下几行创buildcookie:

HttpCookie userid = new HttpCookie("userid", objUser.id.ToString()); userid.Expires.AddYears(1); Response.Cookies.Add(userid); 

现在如何使其持久?

因为如果closures浏览器后再次访问同一页面,我无法恢复。

这是你如何做到这一点。

编写持久性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); 

读取持久性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. } 

虽然接受的答案是正确的,但并没有说明原始代码为什么失败。

来自你的问题的错误代码:

 HttpCookie userid = new HttpCookie("userid", objUser.id.ToString()); userid.Expires.AddYears(1); Response.Cookies.Add(userid); 

看看第二行。 到期的基础是包含默认值1/1/0001的Expires属性。 以上代码正在评估到1/1/0002。 此外,评估不会被保存回财产。 相反,Expires属性应该在当前date的基础上设置。

更正后的代码:

 HttpCookie userid = new HttpCookie("userid", objUser.id.ToString()); userid.Expires = DateTime.Now.AddYears(1); Response.Cookies.Add(userid); 

FWIW要非常小心的存储像未使用cookie的用户标识符。 这样做会使您的网站非常容易发生cookie中毒,用户可以轻松模仿其他用户。 如果你正在考虑这样的事情,我强烈推荐直接使用表单authenticationcookie。

 bool persist = true; var cookie = FormsAuthentication.GetAuthCookie(loginUser.ContactId, persist); cookie.Expires = DateTime.Now.AddMonths(3); var ticket = FormsAuthentication.Decrypt(cookie.Value); var userData = "store any string values you want inside the ticket extra than user id that will be encrypted" var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userData); cookie.Value = FormsAuthentication.Encrypt(newTicket); Response.Cookies.Add(cookie); 

然后你可以在ASP.NET页面上随时阅读

 string userId = null; if (this.Context.User.Identity.IsAuthenticated) { userId = this.Context.User.Identity.Name; } 

据我所知你使用ASP.NET身份validation,并设置cookie持久化,你需要设置FormsAuthenticationTicket.IsPersistent = true这是主要的想法。

 bool isPersisted = true; var authTicket = new FormsAuthenticationTicket( 1, user_name, DateTime.Now, DateTime.Now.AddYears(1),//Expiration (you can set it to 1 year) isPersisted,//THIS IS THE MAIN FLAG addition_data); HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, authTicket ); if (isPersisted) authCookie.Expires = authTicket.Expiration; HttpContext.Current.Response.Cookies.Add(authCookie); 

你需要添加这个作为最后一行…

 HttpContext.Current.Response.Cookies.Add(userid); 

当你需要读取cookie的值时,你可以使用类似下面的方法:

  string cookieUserID= String.Empty; try { if (HttpContext.Current.Request.Cookies["userid"] != null) { cookieUserID = HttpContext.Current.Request.Cookies["userid"]; } } catch (Exception ex) { //handle error } return cookieUserID; 

//添加cookie

 var panelIdCookie = new HttpCookie("panelIdCookie"); panelIdCookie.Values.Add("panelId", panelId.ToString(CultureInfo.InvariantCulture)); panelIdCookie.Expires = DateTime.Now.AddMonths(2); Response.Cookies.Add(panelIdCookie); 

//读取cookie

  var httpCookie = Request.Cookies["panelIdCookie"]; if (httpCookie != null) { panelId = Convert.ToInt32(httpCookie["panelId"]); }