【问题标题】:Anti Forgery validation is not working in MVC 4防伪验证在 MVC 4 中不起作用
【发布时间】:2020-12-22 03:05:36
【问题描述】:

我在 mvc4 中创建了一个登录表单和一些其他控制器。我将 [ValidateAntiForgeryToken] 放在控制器上,并将 @Html.AntiForgeryToken() 放在每个视图中。但是登录后当页面被重定向到另一个页面时,它会给出一个错误

所需的防伪表单字段“__RequestVerificationToken”不存在。”

我的示例控制器是

 [HttpPost, ActionName("UserLogin")]
    [ValidateAntiForgeryToken]
    [AllowAnonymous]
    public ActionResult UserLogin(FormCollection collection)
    {
        string username = collection["txtUser"].ToString();
        string password = collection["pwd"].ToString();
        string Browser = HttpContext.Request.Browser.Browser;
        if (db.Users.Any(u => u.Email == username && u.Password == password))
        {
            User usr = db.Users.Single(u => u.Email == username && u.Password == password);
            return RedirectToAction("Details","User",usr.Id);
        }
        return HttpNotFound();
    }

视图是

@using(Html.BeginForm("UserLogin","User")){
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
/// .......form elements....//
}

【问题讨论】:

  • 在您的表单中查看。尝试添加此 @using(Html.BeginForm("UserLogin","User", FormMethod.Post)) 以确保它重定向到您的控制器的发布操作

标签: c# asp.net-mvc asp.net-mvc-4 antiforgerytoken


【解决方案1】:

我在方法中添加了If ModelState.IsValid Then。这导致模型在验证中正常工作。

@Using Html.BeginForm("request_a_quote", "Furniture_Assembly_Quote", FormMethod.Post, New With {.class = "form-horizontal", .role = "form"})

    @Html.AntiForgeryToken()

    @<text>

        <div Class="row">
                <div Class="col-md-6">
                    <hr />
                    @Html.ValidationSummary("", New With {.class = "text-danger"})



    <HttpPost>
    <AllowAnonymous>
    <ValidateAntiForgeryToken>
    Public Function Request_a_quote(model As RequestViewModel) As ActionResult
        If ModelState.IsValid Then
End If
End Function

【讨论】:

    【解决方案2】:

    RedirectToAction使浏览器根据MSDN向指定的action发出GET请求。您的 AntiForgeryToken 仅在您发布表单时可用。因此,您重定向到的操作不能指望AntiForgeryToken

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-09
      • 2019-06-09
      • 2014-01-23
      • 2014-08-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多