使用 MVC 5.1.1/VS 2013 Professional/.Net 4.5
我偶尔会遇到错误(来自本地主机和生产 IIS 7):
System.Web.Mvc.HttpAntiForgeryException: The anti-forgery cookie token and form field token do not match.
问题似乎是当我注销用户时,有时当我再次进行身份验证时,那是我收到错误的时候。
我的身份验证代码如下所示:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
var user = _uow.UserRepository.FindLogin(model.Email, model.Password);
if (user != null)
{
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Email, user.Email));
claims.Add(new Claim(ClaimTypes.NameIdentifier, user.UserID.ToString()));
claims.Add(new Claim(ClaimTypes.Role, user.UserLevel.ToString()));
var id = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
var ctx = Request.GetOwinContext();
var authenticationManager = ctx.Authentication;
authenticationManager.SignIn(new AuthenticationProperties { IsPersistent = true }, id);
}
else
{
ModelState.AddModelError("", "Invalid Email Address or Password.");
}
}
return View(model);
}
使用 LogOut 方法更新:
[HttpGet]
[AllowAnonymous]
public ActionResult LogOut(LoginViewModel model)
{
Session.Abandon();
return SignOffUser();
}
private ActionResult SignOffUser()
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
return RedirectToAction("Index", "Home");
}
注销表单视图
@if (Request.IsAuthenticated)
{
using (Html.BeginForm(null, null, FormMethod.Post, new {id = "logoutForm", @class = "navbar-right"}))
{
@Html.AntiForgeryToken()
....
}
}
显示您的注销表格(视图)。
如果您从视图中调用控制器中的注销方法,但在表单内部没有产生抗trogergerytoken,就会发生这种情况。
您的表格应该看起来像
然后您通过视图拨打的动作看起来像
PS:无论您的表格如何调用哪种操作方法,如果您想拥有需要验证的抗togrigergery令牌,则表格和动作方法应该看起来像我上面提到的内容。