我有一个标准的 ASP.NET MVC(RC 刷新)Web 项目,具有标准的 ASP.NET 成员资格提供程序和项目模板中包含的帐户控制器。
当我在登录表单中选中“记住我”时,网站仍然没有记住我。(Firefox 记住了我的用户名和密码,但我期望发生的是自动登录)。
我必须手动设置和检查 cookie 吗?如果是这样,最好怎么做?
我有一个标准的 ASP.NET MVC(RC 刷新)Web 项目,具有标准的 ASP.NET 成员资格提供程序和项目模板中包含的帐户控制器。
当我在登录表单中选中“记住我”时,网站仍然没有记住我。(Firefox 记住了我的用户名和密码,但我期望发生的是自动登录)。
我必须手动设置和检查 cookie 吗?如果是这样,最好怎么做?
您需要将 true/false 传递给 SetAuthCookie 方法。
public ActionResult Login (string email, string password, bool rememberMe, string returnUrl)
{
// snip
FormsAuth.SetAuthCookie(username, rememberMe); // <- true/false
// snip
}
并确保它bool rememberMe
反映了登录页面上复选框的状态。
您需要在检查记住ME框时处理登录的控制器方法中生成持久cookie。如果您正在使用RedirectFromLoginPage
,请将 createPersistentCookie 参数设置为true
。
这 3 种方法帮助我持久化 cookie。
请注意,如果用户取消选择“记住我”,您将需要删除 cookie。
private const string RememberMeCookieName = "MyCookieName";
private string CheckForCookieUserName()
{
string returnValue = string.Empty;
HttpCookie rememberMeUserNameCookie = Request.Cookies.Get(RememberMeCookieName);
if (null != rememberMeUserNameCookie)
{
/* Note, the browser only sends the name/value to the webserver, and not the expiration date */
returnValue = rememberMeUserNameCookie.Value;
}
return returnValue;
}
private void CreateRememberMeCookie(string userName)
{
HttpCookie rememberMeCookie = new HttpCookie(RememberMeCookieName, userName);
rememberMeCookie.Expires = DateTime.MaxValue;
Response.SetCookie(rememberMeCookie);
}
private void RemoveRememberMeCookie()
{
/* k1ll the cookie ! */
HttpCookie rememberMeUserNameCookie = Request.Cookies[RememberMeCookieName];
if (null != rememberMeUserNameCookie)
{
Response.Cookies.Remove(RememberMeCookieName);
rememberMeUserNameCookie.Expires = DateTime.Now.AddYears(-1);
rememberMeUserNameCookie.Value = null;
Response.SetCookie(rememberMeUserNameCookie);
}
}