如何在cookie中存储字符串并检索它

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

写一个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("

The cookie has been written.");

读一个cookie

 HttpCookie myCookie = Request.Cookies["MyTestCookie"]; // Read the cookie information and display it. if (myCookie != null) Response.Write("

"+ myCookie.Name + "

"+ myCookie.Value); else Response.Write("not found");

除了Shai所说的,如果你以后想要更新相同的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);