C# jQuery 将 null 而不是 JSON 发布到 ASP.NET Web API

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14779679/
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-10 12:58:39  来源:igfitidea点击:

jQuery posts null instead of JSON to ASP.NET Web API

c#jqueryasp.net-web-apihttp-post

提问by Nicros

I can't seem to get this to work... I have some jQuery like this on the client:

我似乎无法让它工作......我在客户端上有一些像这样的jQuery:

$.ajax({
    type: "POST",
    url: "api/report/reportexists/",
    data: JSON.stringify({ "report":reportpath }),
    success: function(exists) {
        if (exists) {
            fileExists = true;
        } else {
            fileExists = false;
        }
    }
});

And in my Web.API controller I have a method like this:

在我的 Web.API 控制器中,我有一个这样的方法:

[HttpPost]
public bool ReportExists( [FromBody]string report )
{
    bool exists = File.Exists(report);
    return exists;
}

I'm just checking to see if a file lives on the server, and to return a bool as to whether it does or not. The report string I am sending is a UNC path, so reportpath looks like '\\some\path\'.

我只是检查文件是否存在于服务器上,并返回一个布尔值是否存在。我发送的报告字符串是一个 UNC 路径,所以 reportpath 看起来像 '\\some\path\'。

I can fire the script okay, and hit a breakpoint in my ReportExists method, but the report variable is always null.

我可以正常触发脚本,并在我的 ReportExists 方法中遇到断点,但报告变量始终为空。

What am I doing wrong?

我究竟做错了什么?

I also see a way to post with .post and postJSON. Maybe I should be using one of those? If so, what would my format be?

我还看到了一种使用 .post 和 postJSON 发布的方法。也许我应该使用其中之一?如果是这样,我的格式是什么?

Update:An additional clue maybe- if I remove [FromBody] then my breakpoint doesnt get hit at all- 'No http resource was found that matches the request'. Examples I am looking at show that [FromBody] isn't needed...?

更新:可能还有一个额外的线索——如果我删除 [FromBody],那么我的断点根本不会被击中——“找不到与请求匹配的 http 资源”。我正在查看的示例表明不需要 [FromBody] ......?

采纳答案by Nicros

So I found the problem, and the solution. So, first thing first. The contentType cannot be 'application/json', it has to be blank (default to application/x-www-form-urlencoded I believe). Although it seems you have to SEND json, but without a name in the name value pair. Using JSON.stringify also messes this up. So the full working jQuery code is like this:

所以我找到了问题,以及解决方案。所以,第一件事。contentType 不能是“application/json”,它必须是空白的(我相信默认为 application/x-www-form-urlencoded)。虽然看起来您必须发送 json,但名称值对中没有名称。使用 JSON.stringify 也搞砸了。所以完整的 jQuery 代码是这样的:

$.ajax({
    type: "POST",
    url: "api/slideid/reportexists",
    data: { "": reportpath },
    success: function(exists) {
        if (exists) {
            fileExists = true;
        } else {
            fileExists = false;
        }
    }
});

On the Web.API side, you MUST have the [FromBody] attibute on the parameter, but other than this it's pretty standard. The real problem (for me) was the post.

在 Web.API 方面,您必须在参数上具有 [FromBody] 属性,但除此之外,它是非常标准的。真正的问题(对我来说)是帖子。

In Fiddler, the request body looked like this "=%5C%5Croot%5Cdata%5Creport.html"

在 Fiddler 中,请求正文如下所示“=%5C%5Croot%5Cdata%5Creport.html”

Thispost really had the answer, and linked to thisarticle which was also very helpful.

这篇文章确实有答案,并链接到这篇文章,这也很有帮助。

回答by Maggie Ying

jQuery.ajax()by default sets the contentType to be application/x-www-form-urlencoded. You could send the request in application/jsoninstead. Also, you should send your data as a string and it will get model bind to the reportparameter for your post method:

jQuery.ajax()默认情况下将 contentType 设置为application/x-www-form-urlencoded. 您可以application/json改为发送请求。此外,您应该将数据作为字符串发送,它会将模型绑定到report您的 post 方法的参数:

$.ajax({
    type: "POST",
    url: "api/report/reportexists/",
    contentType:  "application/json",
    data: JSON.stringify(reportpath),
    success: function(exists) {
        if (exists) {
            fileExists = true;
        } else {
            fileExists = false;
        }
    }
});

回答by Nicros

This worked for me, all other approaches didn't:

这对我有用,所有其他方法都没有:

function addProduct() {
        var product = { 'Id': 12, 'Name': 'Maya', 'Category': 'newcat', 'Price': 1234 };             
        $.ajax({
            type: "POST",
            url: "../api/products",
            async: true,
            cache: false,
            type: 'POST',
            data: product,
            dataType: "json",
             success: function (result) {

            },
            error: function (jqXHR, exception) {
                alert(exception);
            }
        });
    }

Serverside:

服务器端:

 [HttpPost]
    public Product[] AddNewProduct([FromBody]Product prod)
    {
        new List<Product>(products).Add(prod);
        return products;
    }

回答by Pratik Patel

$.post served the purpose for me. Remove the [FromBody] from webapi and give the url in the url parameter of the $.post in jquery client. It worked!

$.post 为我服务。从webapi中删除[FromBody],并在jquery客户端的$.post的url参数中给出url。有效!

回答by abbottdev

If you're using MVC's FromBodyattribute, the MVC binder treats this as an optional parameter. This means you need to be explicitabout the Parameter names even if you've only got a single FromBodyparameter.

如果您使用 MVC 的FromBody属性,MVC 绑定器会将其视为可选参数。这意味着即使您只有一个参数,您也需要明确说明参数名称FromBody

You should be able to work with something as simple as this:

你应该能够处理像这样简单的事情:

Controller:

控制器:

[HttpPost]
public bool ReportExists( [FromBody]string report )
{
    bool exists = File.Exists(report);
    return exists;
}

Javascript:

Javascript:

$.ajax({
    type: "POST",
    url: "api/report/reportexists/",
    data: { "report":reportpath },
    success: function(exists) {
    ...

You must ensure that your data object in jQuery matches the parameter names of your Controllers exactly.

您必须确保 jQuery 中的数据对象与控制器的参数名称完全匹配。