已解决 - 请求标头应为RequestVerificationToken而不是XSRF-TOKEN
ASP.NET Core Razor页面中的AJAX POST不起作用.它总是返回400 Bad Request.
我有以下页面方法代码:
[ValidateAntiForgeryToken]
public async Task<IActionResult> OnPostProcessCCPaymentAsync(CheckInPaymentModel checkInPaymentModel)
{
return new JsonResult(checkInPaymentModel.AmountExtra);
}
Run Code Online (Sandbox Code Playgroud)
在页面中设置以下内容:
@Html.AntiForgeryToken()
Run Code Online (Sandbox Code Playgroud)
以下JS AJAX调用:
$.ajax({
type: "POST",
url: "/CheckIn/Payment?handler=ProcessCCPayment",
contentType: "application/json",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: JSON.stringify({
// Those property names must match the property names of your PromotionDecision view model
Donate: true
}),
success: function (response) {
$(".paymentDetails .loading").addClass("loader").removeClass("loading");
},
failure: function (response) {
$(".paymentDetails .loading").addClass("loader").removeClass("loading");
}
});
Run Code Online (Sandbox Code Playgroud)
如果Ajax类型更改为GET并且方法更改为OnGetProcessCCPaymentAsync,则它会正确地发送到服务器.
但是,Core Razor中的AJAX POST总是因400 Bad Request而失败.
我直接从Visual …