首页 > 解决方案 > Asp.Net Core Unobtrusive Ajax 在实时服务器上抛出 400 错误

问题描述

我的每一个表格都是类型

 <form id="addform" asp-area="Admin" asp-controller="Departments" asp-action="Add" data-ajax="true" data-ajax-method="post" data-ajax-success="onSuccess" data-ajax-failure="onFailure" data-ajax-begin="onBegin">
</form>

我还在每个 ajaxSend 请求上附加了 RequestVerificationToken

$(document).ajaxSend(function (e, xhr, options) {
    debugger;
    if (options.type.toUpperCase() == "POST") {
        var token = $("input[name='__RequestVerificationToken']").val();
        xhr.setRequestHeader("__RequestVerificationToken", token);
    }
});

我的控制器是这样的

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Add(DepartmentViewModel departmentViewModel)
{
     return View();
}

现在,它在本地运行良好,但在实时服务器上无法正常运行。一些请求工作正常,在几次请求后它返回 400 bad request 错误。

我尝试了很多东西,但都是徒劳的。我需要这种安全性,否则我会跳过相同的

标签: asp.net-mvcasp.net-corecsrfunobtrusive-ajax

解决方案


标题名称应该RequestVerificationToken没有前导下划线。如果您将其作为表单值发布,则带有下划线的版本是您应该使用的名称。您可以将其配置为其他内容:

https://www.learnrazorpages.com/security/request-verification#configuration


推荐阅读