自从升级到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安装


当前回答

我有一个类似的问题,有或没有[FromBody]标签时,通过AJAX调用发送原始数据上传图像。当请求太大时,控制器会转储它(变量= null),所以解决方案是增加最大请求大小,调整图像大小或类似的方法。

增加请求大小的方法描述在这里:https://stackoverflow.com/a/16403447

其他回答

我知道这不是问题的答案,但我在寻找解决问题的方法时偶然发现了它。

在我的情况下,复杂类型没有被绑定,但我没有做一个POST,我正在做一个GET与查询字符串参数。解决方案是在参数中添加[FromUri]:

public class MyController : ApiController
{
    public IEnumerable<MyModel> Get([FromUri] MyComplexType input)
    {
        // input is not null as long as [FromUri] is present in the method arg
    }
}

这招对我很管用:

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"

我一直在寻找这个问题的解决方案,所以我将分享我的解决方案。

如果你发布一个模型,你的模型需要有一个空的/默认的构造函数,否则模型显然不能被创建。 重构时要小心。;)

问题是你的动作方法期望一个简单的类型,即字符串参数值。您所提供的是一个对象。

你的问题有两个解决方案。

创建一个具有“value”属性的简单类,然后将该类用作参数,在这种情况下,Web API模型绑定将从请求中读取JSON对象,并将其绑定到参数对象“values”属性。 只要传递字符串值“test”,它就会工作。