在 jquery ajax post 到 MVC 控制器上不断收到 400(错误请求)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14281537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:24:59  来源:igfitidea点击:

Continually receiving 400 (Bad Request) on jquery ajax post to MVC controller

jquerypostasp.net-mvc-4

提问by Pseudonym

My ajax call looks like this

我的 ajax 调用看起来像这样

$.ajax({ //actually approve or reject the promotion
                url: url,
                type: "POST",
                data: '{'+data.PromotionId+','+data.UserId+','+data.ReasonText+'}',
                dataType: "json",
                //contentType: "application/json; charset=utf-8",
                success: function (data) {
                    if (indicator == 'A') {
                        alert('Promotion approved successfully!');
                    }
                    else {
                        alert('Promotion rejected successfully.');
                    }

                    var homelink = '<%: Url.Action("Index","Home") %>';
                    window.location.href = (homelink);


                    returndata = data;
                },
                error: function (xhRequest, ErrorText, thrownError) {
                    alert("Failed to process promotion correctly, please try again");
                    console.log('xhRequest: ' + xhRequest + "\n");
                    console.log('ErrorText: ' + ErrorText + "\n");
                    console.log('thrownError: ' + thrownError + "\n");
                }
            });

And my MVC controller looks like this:

我的 MVC 控制器如下所示:

 [HttpPost]
    public HttpResponseMessage ApprovePromotion(PromotionDecision decision)
    {
        if (ModelState.IsValid && decision != null)
        {
            bool status = PromotionBo.ApprovePromotion(decision);
            if (status == true)
                return new HttpResponseMessage(HttpStatusCode.OK);
        }
        return new HttpResponseMessage(HttpStatusCode.BadRequest);
    }

I had thought the syntax was correct on both of these however every time I make the ajax call I get a 400 response. What is it that I am doing wrong?

我曾认为这两种语法都是正确的,但是每次我进行 ajax 调用时,我都会收到 400 响应。我做错了什么?

回答by Darin Dimitrov

You are sending a completely broken and invalid JSON string to the server. It's normal that the controller action rejects it. In addition to that you have put into comments the contentTypeparameter specifying that you want to send a JSON request.

您正在向服务器发送一个完全损坏且无效的 JSON 字符串。控制器动作拒绝它是正常的。除此之外,您已将contentType指定要发送 JSON 请求的参数放入注释中。

So here's the correct way to do the request:

因此,这是执行请求的正确方法:

$.ajax({ //actually approve or reject the promotion
    url: url,
    type: "POST",
    data: JSON.stringify({ 
        // Those property names must match the property names of your PromotionDecision  view model
        promotionId: data.PromotionId, 
        userId: data.UserId, 
        reasonText: data.ReasonText
    }),
    contentType: "application/json; charset=utf-8",
    success: function (data) {
        if (indicator == 'A') {
            alert('Promotion approved successfully!');
        }
        else {
            alert('Promotion rejected successfully.');
        }

        var homelink = '<%: Url.Action("Index","Home") %>';
        window.location.href = (homelink);

        returndata = data;
    },
    error: function (xhRequest, ErrorText, thrownError) {
        alert("Failed to process promotion correctly, please try again");
        console.log('xhRequest: ' + xhRequest + "\n");
        console.log('ErrorText: ' + ErrorText + "\n");
        console.log('thrownError: ' + thrownError + "\n");
    }
});

Notice how I am using the JSON.stringifymethod that is natively built-into modern browsers to ensure that the JSON being sent to the server is correctly and all values are properly encoded. And if you need to support browsers from the stone age, you could include the json2.jsscript to your page which will define the JSON.stringifymethod.

请注意我如何使用JSON.stringify现代浏览器本机内置的方法来确保发送到服务器的 JSON 正确且所有值都正确编码。如果您需要支持石器时代的浏览器,您可以将json2.js脚本包含在您的页面中,该脚本将定义该JSON.stringify方法。

Important remark: Absolutely neverbuild JSON strings using string concatenations as in your code.

重要说明:绝对不要像在代码中那样使用字符串连接来构建 JSON 字符串。

Alternatively if you don't want to send a JSON request you could send a standard application/x-www-form-urlencodedrequest:

或者,如果您不想发送 JSON 请求,您可以发送标准application/x-www-form-urlencoded请求:

$.ajax({ //actually approve or reject the promotion
    url: url,
    type: "POST",
    data: { 
        promotionId: data.PromotionId, 
        userId: data.UserId, 
        reasonText: data.ReasonText
    },
    success: function (data) {
        if (indicator == 'A') {
            alert('Promotion approved successfully!');
        }
        else {
            alert('Promotion rejected successfully.');
        }

        var homelink = '<%: Url.Action("Index","Home") %>';
        window.location.href = (homelink);

        returndata = data;
    },
    error: function (xhRequest, ErrorText, thrownError) {
        alert("Failed to process promotion correctly, please try again");
        console.log('xhRequest: ' + xhRequest + "\n");
        console.log('ErrorText: ' + ErrorText + "\n");
        console.log('thrownError: ' + thrownError + "\n");
    }
});

This should work the same way and the controller action should be able to properly bind the model.

这应该以相同的方式工作,并且控制器操作应该能够正确绑定模型。

Remark: I have noticed that you used the following line in your success callback: returndata = data;. This leads me to believe that you are somehow attempting to consume the result of an asynchronous AJAX request outside of the success callback which is not possible. I have no idea what you are doing with this returndatavariable but I feel it is wrong.

备注:我注意到,您使用的下面一行在你的成功回调:returndata = data;。这让我相信您以某种方式试图在成功回调之外使用异步 AJAX 请求的结果,这是不可能的。我不知道你在用这个returndata变量做什么,但我觉得这是错误的。

回答by ticky

This error also occurs when using [ValidateAntiForgeryToken]attribute for MVC action method in combination with Ajax call.

[ValidateAntiForgeryToken]将 MVC 操作方法的属性与 Ajax 调用结合使用时,也会发生此错误。

Check this out, might help as well: https://stackoverflow.com/a/60952294/315528

看看这个,也可能有帮助:https: //stackoverflow.com/a/60952294/315528