2011-12-13 60 views
8

我想将用户名存储在cookie中,并在用户下次打开网站时检索它。是否可以创建一个在浏览器关闭时不会过期的cookie。我正在使用asp.net c#来创建网站。而如何从提供保存用户名和密码如何将字符串存储在cookie中并检索它

+0

请检查这个 http://stackoverflow.com/questions/8485186/how-to-set-remember-me-in-login-page-without-using-membeship-in-mvc-2-0/8485215#8485215 –

回答

22

写一个cookie

HttpCookie myCookie = new HttpCookie("MyTestCookie"); 
DateTime now = DateTime.Now; 

// Set the cookie value. 
myCookie.Value = now.ToString(); 
// Set the cookie expiration date. 
myCookie.Expires = now.AddYears(50); // For a cookie to effectively never expire 

// Add the cookie. 
Response.Cookies.Add(myCookie); 

Response.Write("<p> The cookie has been written."); 

读一个cookie

HttpCookie myCookie = Request.Cookies["MyTestCookie"]; 

// Read the cookie information and display it. 
if (myCookie != null) 
    Response.Write("<p>"+ myCookie.Name + "<p>"+ myCookie.Value); 
else 
    Response.Write("not found"); 
+0

Add参考文献@Shai https://msdn.microsoft.com/zh-cn/library/aa287547(v=vs.71).aspx – Danilo

2

除了什么夏嘉曦说,如果你以后要停止浏览器更新相同的cookie使用:

HttpCookie myCookie = Request.Cookies["MyTestCookie"]; 
DateTime now = DateTime.Now; 

// Set the cookie value. 
myCookie.Value = now.ToString(); 

// Don't forget to reset the Expires property! 
myCookie.Expires = now.AddYears(50); 
Response.SetCookie(myCookie); 
+0

这可能更适合作为评论而不是答案。 – Kmeixner

相关问题