2011-12-13 82 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

相關問題