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


当前回答

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

{
    "value": "test"
}

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

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

"test"

其他回答

如果您正在为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;并且我的输入参数不再为空。感谢《亡命之徒》给了我一个提示。

我尝试了这个帖子中的许多答案,但没有一个对我有用。然后我在一个类似的帖子中看到了这个答案:https://stackoverflow.com/a/40853424/2120023,他提到HttpContext. request . body,所以另一个搜索,我发现这个https://stackoverflow.com/a/1302851/2120023给了我HttpContext。当前,所以我终于得到了这个工作使用:

HttpContext.Current.Request.Form.Get("value");

邮差的要求:

curl --location --request POST 'https://example.com/token' --header 'Content-Type: application/x-www-form-urlencoded' --data-urlencode 'value=test'

我在《小提琴手》里也遇到了同样的问题。我已经有Content-Type: application/json;请求头中的charset=utf-8或Content-Type: application/json。

我的请求体也是一个普通的字符串,在Fiddler中我写了:{'controller':'ctrl'}。这使得POST方法中的字符串参数为空。

修正:记住使用引号,从而表示字符串。也就是说,我通过编写“{'controller':'ctrl'}”来修复它。(注意:在编写JSON时,要么一定要使用撇号,要么像这样转义引号:"{\"controller\":\"ctrl\"}")。

JSON.stringify(…)解决了我的问题

这个链接帮助了我:http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/

基本上,它说你应该为参数使用一个空名称:

public string Post([FromBody]string myParameter){ 
...
}  

$.post("/api/dosomething", { '' : "myvalue" });