如何正确使用ValidateAntiForgeryToken?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何正确使用ValidateAntiForgeryToken?相关的知识,希望对你有一定的参考价值。

我以弹出形式使用验证,但对我不起作用。没有评论时,我按“创建”按钮,但没有任何反应。但是当我发表评论时,一切顺利。我用了两种方法在控制器EmployeesController中

    // POST: Employees/Create
            [HttpPost]
            **[ValidateAntiForgeryToken]**
            public async Task<IActionResult> Create([FromBody] Employee employee)
            {
                if (ModelState.IsValid)
                {
                    if (employee == null)
                    {
                        View(employee);
                    }
                    _context.Add(employee);
                    await _context.SaveChangesAsync();
                    return PartialView("EmployeeList", _context.Employees.ToList());
                }

                ViewData["PositionId"] = new SelectList(_context.Positions, "PositionId", "PositionId", employee.PositionId);
                return View(employee);
            }

和在PositionsController.cs中

[HttpPost]
            [ValidateAntiForgeryToken]
            public async Task<IActionResult> Create([Bind("PositionId,PositionName")] Position position)
            {
                if (ModelState.IsValid)
                {
                    _context.Add(position);
                    await _context.SaveChangesAsync();
                    return PartialView("PositionList", _context.Positions.ToList());
                }
                return View(position);
            }

这是打开弹出窗口的JS

$("#addPosition").click(function() {

    $.ajax({url: $(this).attr("formaction"),
    }).done(function(msg) {
        $("#AddPosition").html(msg);
        $("#add-position").modal("show");
    });
});

$("#save-position").off("click").on("click",
    function (e) {
        e.preventDefault();
        var form = $('form');
        **var token** = $('input[name="__RequestVerificationToken"]', form).val();
        $.ajax({
            type: "post",
            url: form.attr('action'),
            data: {
                **//__RequestVerificationToken: token,**
                position: {
                    PositionName: $("#PositionName").val()
                }
            },
            dataType: "html",
            success: function(result) {
                $("#add-position").modal("hide");
                $("#partial").html(result);
            }
        });
        return false;
    });

$("#addEmployee").click(function() {

    $.ajax({url: $(this).attr("formaction")
    }).done(function(msg) {
        $("#AddEmployee").html(msg);
        $("#add-employee").modal("show");
    });
});
$("#save-employee").off("click").on("click",
    function () {
        var form = $('form');
        **var token** = $('input[name="__RequestVerificationToken"]', form).val();
        var _data = {
            **//__RequestVerificationToken: token,**
            FistName: $("#FistName").val(),
            LastName: $("#LastName").val(),
            PositionId: parseInt($("#PositionId").val()),
            Salary: parseFloat($("#Salary").val()),
            DateStart: $("#DateStart").val(),
            DateEnd: $("#DateEnd").val()
        }

        $.ajax({
            type: "post",
            url: form.attr('action'),
            data: JSON.stringify(_data),
            dataType: "html",
            contentType: "application/json; charset=utf-8",
            success: function(result) {
                $("#add-employee").modal("hide");
                $("#partial").html(result);
                location.reload();
            }
        });
        return false;
    });

这是我的模特

public class Employee
{
    [Key] 
    public int EmployeeId { get; set; }
    [Required] 
    public string FistName { get; set; }
    [Required] 
    public string LastName { get; set; }

    [Required(ErrorMessage = "Enter Position")]
    public int PositionId { get; set; }
    public Position Position { get; set; }
}

这是PartialView

<table class="table">
    <tr>
        <th>Fist Name</th>
        <th>Last Name</th>
        <th>Position</th>
        <th>Salary</th>
        <th>Date Start</th>
        <th>Date End</th>
    </tr>
    @foreach (var item in Model)
    {
        <tr>
            <td>@item.FistName</td>
            <td>@item.LastName</td>
            <td>@item.Position.PositionName</td>
            <td>@item.Salary</td>
            <td>@item.DateStart</td>
            <td>@item.DateEnd</td>

            <td>
                <a asp-action="Edit" asp-route-id="@item.EmployeeId">Edit</a> |
                <a asp-action="Details" asp-route-id="@item.EmployeeId">Details</a> |
                <a asp-action="Delete" asp-route-id="@item.EmployeeId">Delete</a>
            </td>

        </tr>
    }
</table>

这是视图

@{
    ViewData[index: "Title"] = "Create";
}

<h3>Create Employee</h3>
<hr/>
<div class="modal-dialog" role="document">
    <div class="modal-content">
        <div class="modal-header">
            <h5 class="modal-title" id="addEmployeeLabel">Add Employee</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
        <div class="modal-body">
            <form asp-action="Create">
                <input name="IsValid" type="hidden" value="@ViewData.ModelState.IsValid.ToString()"/>
                <div class="form-group">
                    <label asp-for="FistName"></label>
                    <input asp-for="FistName" class="form-control"/>
                    <span asp-validation-for="FistName" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <label asp-for="LastName"></label>
                    <input asp-for="LastName" class="form-control"/>
                    <span asp-validation-for="LastName" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <label asp-for="Position" class="control-label"></label>
                    @Html.DropDownList("PositionId", (IEnumerable<SelectListItem>) ViewData["PositionId"], "- Select -", new {id = "PositionId"})
                    <span asp-validation-for="Position" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <label asp-for="Salary"></label>
                    <input asp-for="Salary" class="form-control"/>
                    <span asp-validation-for="Salary" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <label asp-for="DateStart"></label>
                    <input asp-for="DateStart" class="form-control"/>
                    <span asp-validation-for="DateStart" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <label asp-for="DateEnd"></label>
                    <input asp-for="DateEnd" class="form-control"/>
                    <span asp-validation-for="DateEnd" class="text-danger"></span>
                </div>
            </form>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary" data-save="modal" id="save-employee">Save</button>
        </div>
    </div>
</div>
答案

为简单起见,无需使用js,只需如下更改您的模式即可:

Create.cshtml:

@model TestForApriorit.Models.Employee
@{ 
    Layout = null;
}
<div class="modal-dialog" role="document">
    <div class="modal-content">
        <div class="modal-header">
            <h5 class="modal-title" id="addEmployeeLabel">Add Employee</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
        <div class="modal-body">
            <form asp-action="Create">
                <input name="IsValid" type="hidden" value="@ViewData.ModelState.IsValid.ToString()" />
                <div class="form-group">
                    <label asp-for="FistName"></label>
                    <input asp-for="FistName" class="form-control" />
                    <span asp-validation-for="FistName" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <label asp-for="LastName"></label>
                    <input asp-for="LastName" class="form-control" />
                    <span asp-validation-for="LastName" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <label asp-for="Position" class="control-label"></label>
                    @Html.DropDownList("PositionId", (IEnumerable<SelectListItem>)ViewData["PositionId"], "- Select -", new { id = "PositionId" })
                    <span asp-validation-for="Position" class="text-danger"></span>
                </div>
                //....

                @*change this*@
                <div class="form-group">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <input type="submit" value="Create" class="btn btn-primary" />
                </div>
            </form>
        </div>

    </div>
</div>

Index.cshtml:

<button class="btn btn-primary" asp-controller="Employees" asp-action="Create" data-toggle="ajax-modal" data-target="#add-employee" id="addEmployee">
    Add Employee
</button>

<button class="btn btn-primary" asp-controller="Positions" asp-action="Create"
        data-toggle="ajax-modal" data-target="#add-position" id="addPosition">
    Add Position
</button>

Controller:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Employee employee)
{
    //...
}

结果:enter image description here

以上是关于如何正确使用ValidateAntiForgeryToken?的主要内容,如果未能解决你的问题,请参考以下文章

如何正确使用 Composer 安装 Laravel 扩展包

如何正确的使用SharedPreferences

如何正确强制正确使用类方法?

如何正确使用 Composer 安装 Laravel 扩展包

如何正确使用 AsyncTask? [关闭]

如何正确的使用QWebEngineView