【问题标题】:jQuery posts null instead of JSON to ASP.NET Web APIjQuery 将 null 而不是 JSON 发布到 ASP.NET Web API
【发布时间】:2013-01-24 15:19:31
【问题描述】:

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

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

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

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

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

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

我做错了什么?

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

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

【问题讨论】:

  • $.ajax 更适合这种情况,因为您可能还需要将contentType: "application/json" 作为$.ajax 的选项包含在内
  • 请务必检查您的 ModelState 是否有错误,以防绑定参数时出现问题。

标签: c# jquery asp.net-web-api http-post


【解决方案1】:

所以我找到了问题和解决方案。所以,第一件事。 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;
        }
    }
});

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

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

This 帖子确实有答案,并链接到this 文章,这也很有帮助。

【讨论】:

  • 如果可以的话+1000。唯一完全解决了我的问题的帖子。
  • 是的,当您有一个简单的数据类型并且不使用 DTO 或模型时,这可以工作。我终于放弃了理论上应该有效的一切,只是完全按照这个答案去做,它有效。
  • 如果你有 2 个参数怎么办?!
【解决方案2】:

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

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

【讨论】:

  • 是的,内容类型通常是问题所在。
【解决方案3】:

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

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

服务器端:

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

【讨论】:

  • 我把普通的 JSON 对象交给了我,不需要字符串化!
  • 谢谢,真的谢谢,经过多次搜索终于这对我有用!
【解决方案4】:

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

您应该能够使用像这样简单的东西:

控制器:

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

Javascript

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

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

【讨论】:

    【解决方案5】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-30
      • 2017-10-27
      • 2019-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多