自从升级到RC的WebAPI,我有一些真正奇怪的问题时调用POST在我的WebAPI。 我甚至回到了在新项目上生成的基本版本。所以:

public void Post(string value)
{
}

提琴手喊道:

Header:
User-Agent: Fiddler
Host: localhost:60725
Content-Type: application/json
Content-Length: 29

Body:
{
    "value": "test"
}

当我调试时,字符串“value”永远不会被赋值。它总是NULL。 有人有这个问题吗?

(我第一次看到这个问题是在一个更复杂的类型上)

这个问题不仅仅局限于ASP。在asp.net MVC 4中,同样的问题出现在一个新的ASP。NET MVC 3项目后RC安装


当前回答

这招对我很管用:

Create a C# DTO class, with a property for every attribute you want to pass from jQuery/Ajax public class EntityData { public string Attr1 { get; set; } public string Attr2 { get; set; } } Define the web api method: [HttpPost()] public JObject AddNewEntity([FromBody] EntityData entityData) { Call the web api as such: var entityData = { "attr1": "value1", "attr2": "value2" }; $.ajax({ type: "POST", url: "/api/YOURCONTROLLER/addnewentity", async: true, cache: false, data: JSON.stringify(entityData), contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { ... } });

其他回答

我在使用邮差时也犯了同样的错误。将值作为json对象而不是字符串传递

{
    "value": "test"
}

显然,当api参数的类型是字符串时,上面的一个是错误的。

因此,只需在api体中以双引号传递字符串:

"test"

不管你想要发布什么类型的值,只要把它括在引号里,就可以得到字符串。不适合复杂类型。

javascript:

    var myData = null, url = 'api/' + 'Named/' + 'NamedMethod';

    myData = 7;

    $http.post(url, "'" + myData + "'")
         .then(function (response) { console.log(response.data); });

    myData = "some sentence";

    $http.post(url, "'" + myData + "'")
         .then(function (response) { console.log(response.data); });

    myData = { name: 'person name', age: 21 };

    $http.post(url, "'" + JSON.stringify(myData) + "'")
         .then(function (response) { console.log(response.data); });

    $http.post(url, "'" + angular.toJson(myData) + "'")
         .then(function (response) { console.log(response.data); });

c#:

    public class NamedController : ApiController
    {
        [HttpPost]
        public int NamedMethod([FromBody] string value)
        {
            return value == null ? 1 : 0;
        }
    }

我有同样的问题,获得null作为参数,但它与大对象有关。事实证明,这个问题与IIS最大长度有关。它可以在web.config中配置。

  <system.web>
    <httpRuntime targetFramework="4.7" maxRequestLength="1073741824" />
  </system.web>

我想知道为什么Web API抑制错误并向我的API发送空对象。我使用Microsoft.AspNet.WebApi.Tracing发现了这个错误。

我也遇到过这个问题,这就是我解决问题的方法

webapi守则:

public void Post([FromBody] dynamic data)
{
    string value = data.value;
    /* do stuff */
}

客户机代码:

$.post( "webapi/address", { value: "some value" } );

在我的情况下,问题是参数是一个字符串而不是一个对象,我把参数改为Newsoft的JObject。Json,它可以工作。