ValidateAntiForgeryToken breaks page

时间:2017-06-15 09:33:14

标签: asp.net-core-mvc antiforgerytoken asp.net-core-1.1

I have an ASP .Net Core 1.1 MVC web app. When I add the [ValidateAntiForgeryToken] decoration to my Edit/Delete/Create controllers, the pages don't load ( HTTP 400 error). Any ideas why? I read somewhere that I have to add a corresponding @HtmlHelper.AntiForgeryToken to my Views, or something like that? But not sure where to put it... However, I've also read that it's not necessary to do this anymoer in ASP .Net Core...

Here is an example of my Edit view for a "Users" controller:

@model InspectionsData.Models.User

@{
    ViewData["Title"] = "Edit";
}

<h2>Edit</h2>

<form asp-action="Edit">
    <div class="form-horizontal">
        <h4>User</h4>
        <hr />
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="form-group" hidden>
            <label asp-for="UserId" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input asp-for="UserId" class="form-control" />
                <span asp-validation-for="UserId" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group">
            <label asp-for="FirstName" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input asp-for="FirstName" class="form-control" />
                <span asp-validation-for="FirstName" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group">
            <label asp-for="LastName" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input asp-for="LastName" class="form-control" />
                <span asp-validation-for="LastName" class="text-danger"></span>
            </div>
        </div>
    </div>
</form>

<div>
    <a asp-action="Index">Back to List</a>
</div>

Thank you

2 个答案:

答案 0 :(得分:0)

您需要将表单声明更改为以下内容。

<form asp-controller="User" 
    asp-action="Edit" method="post" asp-antiforgery="true">

就像你提到的那样,asp-antiforgery="true" 可能是可选的,但我喜欢总是添加它以确保我显示我的意图。这对我来说每次都适用。

希望这有帮助。

答案 1 :(得分:0)

是的,你是对的。您不必再在ASP.NET Core中手动放置AntiForgeryToken。

  

Form代码帮助器生成隐藏的请求验证令牌   防止跨站点请求伪造(与使用时)    HTTP Post操作方法中的[ValidateAntiForgeryToken]属性

取自ASP.NET Core docs

话虽如此,您确定自己的行为符合POST请求吗?

同时指定Controller也是一个好主意。

<form asp-controller="Users" asp-action="Edit">

P.S:为行动方法添加代码有助于更快地解决问题。