使用FromBody接收参数

时间:2018-01-29 22:01:27

标签: c# asp.net json web-services

我有一个web服务,我需要接收多个参数,其中一个是列表。

这是网络服务方法:

 [HttpPost("complete/{requestId}")]
 public IActionResult CompleteRequest([FromBody] RequestComplete requestComplete, int requestId)
 {

      if (requestId == 0)
      {
           return BadRequest();
      }

      if (requestComplete == null)
      {
           return BadRequest();
      }
      // execute code
 }

RequestComplete类如下所示:

public class RequestComplete
{
    public int RequestId { get; set; }
    public int UserId { get; set; }
    public string emailCC { get; set; }
    public string emailSubject { get; set; }
    public string calcsNeeded { get; set; }
    public string ssiComment { get; set; }
    public List<CompleteFileUpload> completeFiles { get; set; }

}

这样的CompleteFileUpload类:

public class CompleteFileUpload
{
    public int RequestFileId { get; set; }
}

从PostMan我使用这样的帖子:

{
    "calcsNeeded" : "4",
    "completeFiles": {"RequestFileId": "384"},
    "emailCC" : "test@email.com",
    "emailSubject": "subject here",
    "ssiComment":"Thanks for your request."
}

我的期望是Postman发布的json格式正确,可以被CompleteRequest方法接受。但事实并非如此。如果我删除了json的completeFiles部分,它运行正常。

我错过了什么?

1 个答案:

答案 0 :(得分:1)

&#34; completeFiles&#34;的定义在JSON中没有定义JSON数组,它定义了一个单独的对象。如果定义是:

,那JSON将是有效的
public class RequestComplete
{
    ...
    public CompleteFileUpload completeFiles { get; set; }
}

尝试将JSON更改为:

{
    "calcsNeeded" : "4",
    "completeFiles": [ {"RequestFileId": "384"}, {"RequestFileId": "123"} ],
    "emailCC" : "test@email.com",
    "emailSubject": "subject here",
    "ssiComment":"Thanks for your request."
}

希望这有帮助