【发布时间】:2012-05-14 09:26:22
【问题描述】:
如何一步一步创建 cookie,
当他/她单击记住我时存储用户登录 ID 和密码?选项
我打算在一段时间后杀死这个 cookie
【问题讨论】:
标签: asp.net asp.net-mvc asp.net-mvc-3
如何一步一步创建 cookie,
当他/她单击记住我时存储用户登录 ID 和密码?选项
我打算在一段时间后杀死这个 cookie
【问题讨论】:
标签: asp.net asp.net-mvc asp.net-mvc-3
Cookie 的创建方式与它们在普通旧 ASP.NET 中的创建方式相同,您只需要访问 Response。
public ActionResult Login(string username, string password, bool rememberMe)
{
// validate username/password
if (rememberMe)
{
HttpCookie cookie = new HttpCookie("RememberUsername", username);
Response.Cookies.Add(cookie);
}
return View();
}
但是,如果您使用的是 Forms Auth,则可以让您的 FormsAuth 票证 cookie 持久化:
public ActionResult Login(string username, string password, bool rememberMe)
{
// validate username/password
FormsAuthentication.SetAuthCookie(username, rememberMe);
return View();
}
您可以像这样读取 cookie:
public ActionResult Index()
{
var cookie = Request.Cookies["RememberUsername"];
var username = cookie == null ? string.Empty : cookie.Value; // if the cookie is not present, 'cookie' will be null. I set the 'username' variable to an empty string if its missing; otherwise i use the cookie value
// do what you wish with the cookie value
return View();
}
如果您正在使用表单身份验证并且用户已登录,您可以像这样访问他们的用户名:
public ActionResult Index()
{
var username = User.Identity.IsAuthenticated ? User.Identity.Name : string.Empty;
// do what you wish with user name
return View();
}
可以解密和读取票证的内容。如果需要,您甚至可以在票证中存储少量自定义数据。 See this article for more info.
【讨论】: