【问题标题】:How to handle AutoValidateAntiForgeryToken through ajax callsl in .Net Core 2.2如何在.Net Core 2.2中通过ajax调用处理AutoValidateAntiForgeryToken
【发布时间】:2019-12-11 18:29:47
【问题描述】:

我正在使用.Net Core 2.2,我正在为控制器中的每个操作使用AutoValidateAntiForgeryToken 属性。 提交调用(通过开始表单提交)工作正常,而对于 ajax 调用,控制器操作没有命中 - 我不知道如何处理 AutoValidateAntiForgeryToken 的 ajax 调用。

请帮助我。

谢谢!!!

【问题讨论】:

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


【解决方案1】:

在 .Net Core 2.2 中,对于 ajax 调用,我们需要在 headers 中设置_RequestVerificationToken。 要访问该标头,我们需要将其添加到像

这样的服务中
services.AddAntiforgery(options => options.HeaderName = "__RequestVerificationToken");

这是我的 javascript 代码。

$.ajax({
    headers: {
        "__RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val()
    },
    url: url,
    type: "POST",
    dataType: "html",
    data: request,
    success: function (response) {

        $("#ImageTable").html(response);
        callback(response);
    },
    error: function (xhr, textStatus, errorThrown) {
        //console.log('Error calling rules engine. Error thrown: ' + JSON.stringify(errorThrown) + '. Request: ' + JSON.stringify(request));
    }
});

这是我的控制器操作

    [HttpPost]
    [AutoValidateAntiforgeryToken]
    public async Task<ActionResult> Confirm(string tabId)
    {
      //some code
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-16
    • 2019-07-22
    相关资源
    最近更新 更多