具有多个参数的Web服务函数的Json主体

时间:2014-06-26 19:10:57

标签: json asp.net-web-api

我试图做一个帖子请求,每当我向函数添加第二个参数时都会失败。

例如,这可以使用以下功能:

public class Mock
{
     public String MyFirstValue { get; set; }
     public String MySecondValue { get; set; }
}

[HttpPost]
public ResponseDataDTO TestPost(Mock test)
{
     var response = new ResponseDataDTO();
     return response;
}

使用以下正文请求:

{ 
   "MyFirstValue": "testvalue", 
   "MySecondValue": "testvalue" }
}

然而,当我向这个函数添加另一个参数时,它不再起作用,因为我不太清楚如何构造json:

[HttpPost]
public ResponseDataDTO TestPost(Mock test, Mock test2)
{
      var response = new ResponseDataDTO();
      return response;
}

我对身体的最佳猜测:

{ 
   "test": {
               "MyFirstValue": "testvalue", 
               "MySecondValue": "testvalue"
   }
   "test2": {
               "MyFirstValue": "testvalue2", 
               "MySecondValue": "testvalue2"
   }
}

我之前没有遇到过这些问题,因为我通常只有一个对象参数可以解决这个问题。

我无法工作的另一个奇怪的事情是只有一个整数参数的方法:

[HttpPost]
public ResponseDataDTO TestPostInteger(int test)
{
      var response = new ResponseDataDTO();
      return response;
}

身体:

{ 
   "test" : 1
}

这给了我404,它甚至找不到方法。如果我将参数放在URL中,它就会起作用。

1 个答案:

答案 0 :(得分:2)

响应正文只能绑定到一个对象。

话虽如此,一个解决方案是TestPost接收Mock数组。像这样:

 [HttpPost]
 public ResponseDataDTO TestPost(Mock[] tests)
 { ... }

JSON:

[
   {
       "MyFirstValue": "testvalue", 
       "MySecondValue": "testvalue"
   },
   {
       "MyFirstValue": "testvalue2", 
       "MySecondValue": "testvalue2"
   }
]