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


当前回答

我刚刚使用Fiddler发生了这种情况。问题是我没有指定Content-Type。

尝试在POST请求中包含Content-Type头。

Content-Type: application/x-www-form-urlencoded

或者,根据下面的注释,您可能需要包含一个JSON头

Content-Type: application/json

其他回答

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

{
    "value": "test"
}

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

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

"test"

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

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

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

在Angular中,我可以这样传递数据:

 data: '=' + JSON.stringify({ u: $scope.usrname1, p: $scope.pwd1 }),
 headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8' }

在Web API控制器中:

    [HttpPost]
    public Hashtable Post([FromBody]string jsonString)
    {
        IDictionary<string, string> data = JsonConvert.DeserializeObject<IDictionary<string, string>>(jsonString);
        string username = data["u"];
        string pwd = data["p"];
   ......

或者,我也可以像这样发布JSON数据:

    data: { PaintingId: 1, Title: "Animal show", Price: 10.50 } 

并且,在控制器中,接受这样的类类型:

    [HttpPost]
    public string POST(Models.PostModel pm)
    {

     ....
    }

两种方式都可以,如果你在API中有一个已经建立的公共类,那么就发布JSON,否则就发布'=' + JSON.stringify({..:…, . .:…})

如果您正在为Xml Formatter或JSON Formatter使用DataContractSerializer,则需要摆脱它。 我在我的WebApiConfig文件中有这个:

public static void Register(HttpConfiguration config)
{
     config.Routes.MapHttpRoute(
           name: "DefaultApi",
           routeTemplate: "api/{controller}/{id}",
           defaults: new { id = RouteParameter.Optional }
     );    

     var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
     jsonFormatter.UseDataContractJsonSerializer = true;
}

我简单地注释掉了jsonFormatter。UseDataContractJsonSerializer = true;并且我的输入参数不再为空。感谢《亡命之徒》给了我一个提示。

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

在我的情况下,复杂类型没有被绑定,但我没有做一个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
    }
}