AJAX POST in ASP.NET Core Razor page will not work. It always returns a 400 Bad Request.
I have the following page method code :
[ValidateAntiForgeryToken]
public async Task<IActionResult> OnPostProcessCCPaymentAsync(CheckInPaymentModel checkInPaymentModel)
{
return new JsonResult(checkInPaymentModel.AmountExtra);
}
The following is set in the page :
@Html.AntiForgeryToken()
And the following JS AJAX call :
$.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");
}
});
If the Ajax Type is changed to GET & the method changed to OnGetProcessCCPaymentAsync then it correctly sends to the server.
However the AJAX POST in Core Razor always fails with a 400 Bad Request.
I am debugging directly from Visual Studio so the URL is http://localhost:62632/CheckIn/Payment so I don't know how to locate the logs to see what error is occuring when the debug instance is receiving the request.
Any ideas or advice would be greatly appreciated.
Just so there's no confusion in reading the revisions above and comment (which left me scratching my head for a minute), the solution is to change:
xhr.setRequestHeader("XSRF-TOKEN",
To:
xhr.setRequestHeader("RequestVerificationToken",
The answer is in the revision and the someone edited it out. It's also mentioned briefly in the comments. I'm certainly not taking any credit, just trying to minimize confusion for anyone else that encounters this insanity making error in the future.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With