我最近把Live使用MVC 4和Entity Framework 5构建的Web应用程序.MVC应用程序使用Razor Views。
我注意到使用Elmah,当用户登录应用程序时,有时他们会收到以下错误
The provided anti-forgery token was meant for user "" but the current user is "user"
我已经就如何解决这个问题做了一些研究,但似乎没有什么对我有用。请参阅下面的我的登录视图和相应的控制器操作。
剃刀视图
@if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<div class="formEl_a">
<fieldset>
<legend>Login Information</legend>
<div class="lbl_a">
Email
</div>
<div class="editor-field">
@Html.TextBoxFor(m => m.Email, new { @class = "inpt_a" })<br />
@Html.ValidationMessageFor(m => m.Email)
</div>
<div class="lbl_a">
@Html.LabelFor(m => m.Password)
</div>
<div class="editor-field sepH_b">
@Html.PasswordFor(m => m.Password, new { @class = "inpt_a" })<br />
@Html.ValidationMessageFor(m => m.Password)
</div>
</fieldset>
</div>
<br />
<p>
<input type="submit" value="Log In" class="btn btn_d sepV_a" />
</p>
}
}
调节器
[AllowAnonymous]
public ActionResult Login()
{
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid && _accountService.Logon(model.Email, model.Password, true))
{
//Validate
}
else
{
// inform of failed login
}
}
我觉得这一切看起来还不错,但错误仍然存在。有没有关于如何解决这个问题的想法?
非常感谢您的帮助。
谢谢。
我相信这是因为用户双击表单上的提交按钮。至少在我的网站上确实如此。
针对AntiForgeryToken运行的验证代码还会检查您登录的用户凭据是否未更改 - 这些也在cookie中加密。这意味着,如果您在弹出窗口或其他浏览器选项卡中登录或注销,则表单提交将失败,并出现以下异常:
System.Web.Mvc.HttpAntiForgeryException (0x80004005):
The provided anti-forgery token was meant for user "", but the current user is "SomeOne".
您可以通过将AntiForgeryConfig.SuppressIdentityHeuristicChecks = true;
放入Application_Start
文件中的Global.asax
方法来关闭此功能。
当AntiForgeryToken未验证您的网站时,将抛出类型为System.Web.Mvc.HttpAntiForgeryException
的异常。通过捕获HttpAntiForgeryException,至少为用户提供针对这些异常的信息更丰富的页面,可以使这更容易一些。
private void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
if (ex is HttpAntiForgeryException)
{
Response.Clear();
Server.ClearError(); //make sure you log the exception first
Response.Redirect("/error/antiforgery", true);
}
}
更多信息:
Anti forgery token is meant for user “” but the current user is “username”
我什么时候遇到同样的问题
我发现这只发生在IE中,我通过做几件事来修复它
[AllowAnonymous]
[OutputCache(NoStore=true, Location=System.Web.UI.OutputCacheLocation.None)]
public ActionResult Login)
{
if (HttpContext.Request.IsAuthenticated)
{
WebSecurity.Logout();
Session.Abandon();
return RedirectToAction("Login");
}
return View();
}