我的部署服务器中有这个问题有时而且它让我疯狂,因为我无法在localhost中重现,我尝试在我的web.config中添加机器密钥但是没有运气所以远。
它只发生在登录页面。
我的布局:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<form id="__AjaxAntiForgeryForm" action="#" method="post">
@Html.AntiForgeryToken()
</form>
<div class="wcenter">
@Html.Partial("_LoginPartial")
</div>
<br />
<div class="wcenter">
@RenderBody()
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/bootstrap")
@Scripts.Render("~/bundles/pluginjs")
@Scripts.Render("~/bundles/customjs")
@RenderSection("scripts", required: false)
</body>
</html>
我的登录页面
@model LoginViewModel
@{
ViewBag.Title = "Log in";
}
<h2>@ViewBag.Title.</h2>
@using (Html.BeginForm("Login", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
@Html.LabelFor(m => m.Username)
@Html.TextBoxFor(m => m.Username)
@Html.ValidationMessageFor(m => m.Username)
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password)
@Html.ValidationMessageFor(m => m.Password)
<input type="submit" value="LOGIN" />
}
控制器:
[AllowAnonymous]
public ActionResult Login()
{
if (Request.IsAuthenticated)
{
return RedirectToAction("Index", "Home");
}
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (Request.IsAuthenticated)
{
return RedirectToAction("Index", "Home");
}
if (!ModelState.IsValid)
{
return View(model);
}
var user = new ApplicationUser() { UserName = model.Username, Id = model.Username };
var result = await UserManager.CheckPasswordAsync(user, model.Password);
if (result == true)
{
if (UserManager.FindByName(user.UserName) == null)
{
var res = UserManager.Create(user);
if (!res.Succeeded)
{
ModelState.AddModelError("", res.Errors.FirstOrDefault());
return View(model);
}
}
SignInManager.SignIn(user, true, true);
return RedirectToAction("Index", "Home");
}
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
任何帮助将不胜感激。
答案 0 :(得分:2)
这是因为您正在创建2个Antiforgery令牌,一个在表单内,另一个在您的局部视图中。因此,有时创建的CSR CSR与CSRF输入隐藏字段
不匹配