我正在尝试在我的登录表单中实现“记住我”功能。我使用 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);
}
}
所以基本上,我想我会做的是从主控制器上的索引操作结果重定向用户,以防有登录 cookie。但问题是 RedirectToAction 将触发 GET 登录操作方法,而不是负责登录用户的 POST。
我在这件事上完全错了吗?或者有什么方法可以使用 RedirectToAction 或任何其他方式调用 POST Login 方法?