我正在尝试为我的登录表单实现“记住我”功能。我使用ASP.NET MVC作为我的Web应用程序。我设法使cookie起作用,但是如果用户在之前勾选了“记住我”复选框,则无法自动登录用户。我知道问题所在,但我不知道如何解决它。
在我的HomeController中,我有以下内容:
private LoginViewModel CheckLoginCookie()
{
if (!string.IsNullOrEmpty(_appCookies.Email) && !string.IsNullOrEmpty(_appCookies.Password))
{
var login = new LoginViewModel
{
Email = _appCookies.Email,
Password = _appCookies.Password
};
return login;
}
return null;
}
public ActionResult Index()
{
var login = CheckLoginCookie();
if (login != null)
return RedirectToAction("Login", "User", login);
var viewModel = new HomeIndexViewModel
{
IntroText =
"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
LastMinuteDeals = new List<ItemsIndexViewModel>(),
TrustedDeals = new List<ItemsIndexViewModel>()
};
return View(viewModel);
}
在我的UserController中,我有一个名为Login的操作方法:
public ActionResult Login()
{
return PartialView(new LoginViewModel());
}
[HttpPost]
public ActionResult Login(LoginViewModel dto)
{
bool flag = false;
if (ModelState.IsValid)
{
if (_userService.AuthenticateUser(dto.Email, dto.Password, false)) {
var user = _userService.GetUserByEmail(dto.Email);
var uSession = new UserSession
{
ID = user.Id,
Nickname = user.Nickname
};
SessionManager.RegisterSession(SessionKeys.User, uSession);
flag = true;
if(dto.RememberMe)
{
_appCookies.Email = dto.Email;
_appCookies.Password = dto.Password;
}
}
}
if (flag)
return RedirectToAction("Index", "Home");
else
{
ViewData.Add("InvalidLogin", "The login info you provided were incorrect.");
return View(dto);
}
}
基本上,我的想法是,在主页控制器的Index操作结果中检查是否有登录cookie,如果有,则将用户重定向。但问题在于,RedirectToAction将触发GET Login操作方法,而不是负责登录用户的POST方法。
我完全错了吗?或者有没有办法使用RedirectToAction或其他方式调用POST Login方法?