自从升级到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.stringify(…)解决了我的问题

其他回答

我尝试了这个帖子中的许多答案,但没有一个对我有用。然后我在一个类似的帖子中看到了这个答案: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'

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

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

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

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

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

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

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

我发现最简单的方法来处理简单的JSON对象,我传递到MVC 6是获得类型的post参数像NewtonSoft jObject:

public ActionResult Test2([FromBody] jObject str)
{
        return Json(new { message = "Test1 Returned: "+ str }); ;
}