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

Nic*_*ros 16 c# jquery http-post asp.net-web-api

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

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

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

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

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

我可以解决脚本问题,并在ReportExists方法中点击断点,但报表变量始终为null.

我究竟做错了什么?

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

更新: 一个额外的线索可能 - 如果我删除[FromBody]然后我的断点根本没有被击中 - '没有找到匹配请求的http资源'.我看的例子表明不需要[FromBody] ......?

Nic*_*ros 25

所以我发现了问题和解决方案.所以,首先要做的事情.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;
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

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

在Fiddler中,请求体看起来像这样"=%5C%5Croot%5Cdata%5Creport.html"

这篇文章真的有了答案,并且链接到这篇文章也很有帮助.


Mag*_*ing 13

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

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

  • 是的,内容类型通常是问题. (3认同)

小智 6

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

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);
            }
        });
    }
Run Code Online (Sandbox Code Playgroud)

服务器端:

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