Reputation: 171
I have a method like this (the parameters name intentionally stupid for this example):
[HttpPost]
[Route("rest/myMethod")]
public IHttpActionResult MyMethod(string param1, DateTime param2, DateTime param3, IEnumerable<string> param4, IEnumerable<string> param5 = null)
{
return Ok();
}
But when I test it in Swagger I get this error:
{
"message": "An error has occurred.",
"exceptionMessage": "Can't bind multiple parameters ('param4' and 'param5') to the request's content.",
"exceptionType": "System.InvalidOperationException",
"stackTrace": ""
}
As soon as I remove one of the two collection parameter this works fine.
Why is that ? How can I POST multiple collections of objects in my WebApi ?
Thanks.
PS: I don't know if this is a usefull piece of intelligence but this WebApi will be called from a AngularJS client.
Upvotes: 1
Views: 613
Reputation: 1039190
How can I POST multiple collections of objects in my WebApi ?
By wrapping them in a view model:
public class MyViewModel
{
public string Param1 { get; set; }
public DateTime Param2 { get; set; }
public DateTime Param3 { get; set; }
public IEnumerable<string> Param4 { get; set; }
public IEnumerable<string> Param5 { get; set; }
}
that your POST action will take as parameter:
[HttpPost]
[Route("rest/myMethod")]
public IHttpActionResult MyMethod(MyViewModel model)
{
return Ok();
}
Now you could have the following request:
POST /rest/myMethod HTTP/1.1
Host: example.com
Content-Type: application/json
Content-Length: 174
Connection: close
{
"Param1": "value of param1",
"Param2": "2017-01-18T07:31:02Z",
"Param3": "2017-01-19T07:31:02Z",
"Param4": [ "foo", "bar" ],
"Param5": [ "baz" ]
}
Upvotes: 2