ASP.NET Core Razor-AJAX发布-400错误的请求 [英] ASP.NET Core Razor - AJAX Post - 400 Bad Request

查看:454
本文介绍了ASP.NET Core Razor-AJAX发布-400错误的请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ASP.NET Core Razor页面中的AJAX POST不起作用.它总是返回400错误请求.

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()

以及以下JS AJAX调用:

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");
    }
});

如果Ajax类型更改为GET&方法更改为OnGetProcessCCPaymentAsync,然后将其正确发送到服务器.

If the Ajax Type is changed to GET & the method changed to OnGetProcessCCPaymentAsync then it correctly sends to the server.

但是,Core Razor中的AJAX POST始终失败,并显示400错误请求.

However the AJAX POST in Core Razor always fails with a 400 Bad Request.

我直接从Visual Studio调试,因此URL为 http://localhost:62632/CheckIn/Payment ,所以我不知道如何找到日志以查看调试实例接收到请求时发生了什么错误.

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.

推荐答案

因此,阅读上面的修订并发表评论时没有任何困惑(这让我ing了一会儿),解决方案是更改:

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",

收件人:

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.

这篇关于ASP.NET Core Razor-AJAX发布-400错误的请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆