Mur*_*hy 15 c# asp.net cookies
我想将用户名存储在cookie中,并在用户下次打开网站时检索它.是否可以创建一个在浏览器关闭时不会过期的cookie.我正在使用asp.net c#来创建网站.如何阻止浏览器提供保存用户名和密码
Sha*_*hai 35
写一个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.");
Run Code Online (Sandbox Code Playgroud)
读一个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");
Run Code Online (Sandbox Code Playgroud)
除了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);
Run Code Online (Sandbox Code Playgroud)