ASP.NET Core Razor - AJAX Post - 400 Bad Request

[亡魂溺海] 提交于 2020-07-08 04:05:50

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/50064246/asp-net-core-razor-ajax-post-400-bad-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!