我正在为 MVC 网站使用表单例份验证,但在添加 Cookie 时遇到问题,我正在使用加密表单例份验证票并将其添加到 Cookie 中,但是在检查我的 cookie 时,它在那里(名称为“AuthCookie”)但值始终为空并且到期日期始终设置为“01/01/0001 00:00”...这是我的登录 Controller 代码:
[HttpPost]
public ActionResult Index(Login login, string returnUrl)
{
if (ModelState.IsValid)
try
{
User user = UserManager.Login(login.Username, login.Password);
string serialUser = Serialize.SerializeToString(user);
string ticket = FormsAuthentication.Encrypt(
new FormsAuthenticationTicket(1, login.Username, DateTime.Now, DateTime.Now.AddMinutes(20.0), login.RemeberMe, serialUser));
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticket) { Expires = DateTime.Now.AddMinutes(20) };
Response.Cookies.Add(cookie);
if (String.IsNullOrEmpty(returnUrl))
return RedirectToAction("Index", "Home");
else
return Redirect(returnUrl);
}
catch (LoginFailedException)
{
ModelState.AddModelError("", "Login failed: Invalid Username or Password.");
return View(login);
}
else
return View(login);
}
起初,我认为加密字符串由于长度而无法正常工作,但我已经通过创建一个简单的测试库对此进行了测试,并且得到了相同的结果。
谁能帮忙
最佳答案
当您调用 Redirect() 或 RedirectToAction() 时,您将终止响应,因此 cookie 不会发送到客户端。一些解决方案:
关于asp.net-mvc-3 - MVC 3 Cookie 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8696464/