Skip to main content
 首页 » 编程设计

c#之Web API [FromBody] 参数在发送对象数组时为空

2024年02月05日30lhb25

我似乎遇到了一个有趣的 Web API 问题 - 使用这个 Controller 操作,在左大括号上设置断点来检查 thing:

[HttpPut] 
public void Test([FromBody]object thing) 
{ 
} 

如果我提交以下请求(作为 CURL),我会得到期望值,它是一个包含正文数据的 JObject:

curl -X PUT -H "Content-Type: application/json" -d '{ 
    "Name": "Joe", 
    "Key": { "Key": "Value" } 
}' "http://localhost/api/TestController/Test" 

也就是说,一个匿名对象,其中 Name 是 Joe,Key 是另一个包含 Key = Value 的对象。

但是,如果我稍微更改它以提交一个 Keys 数组,我将得到 null。没有错误,只是 null。

curl -X PUT -H "Content-Type: application/json" -d '{ 
    "Name": "Joe", 
    "Keys": [{ "Key": "Value" }] 
}' "http://localhost/api/TestController/Test" 

为什么会这样? HTTP 动词似乎并不重要(我试过 POST 和 PUT),使用 dynamic 而不是 object 是一回事。

以下是部分截图:

请您参考如下方法:

您的代码在 Postman 中测试时运行良好。