I need to create a HttpGet method with two List parameters, but I'm getting this error:
has more than one parameter that was specified or inferred as bound from request body. Only one parameter per action may be bound from body. Inspect the following parameters, and use 'FromQueryAttribute' to specify bound from query, 'FromRouteAttribute' to specify bound from route, and 'FromBodyAttribute' for parameters to be bound from body:
MyObject
has two properties:
public class MyObject
{
public int Prop1 { get; set; }
public int Prop2 { get; set; }
}
Things I tried that throw exception above
Method 1
[HttpGet]
public IActionResult Get(List<MyObject> obj1, List<MyObject> obj2)
Method 2
[HttpGet]
[Route("{obj1}/{obj2")]
public IActionResult Get(List<MyObject> obj1, List<MyObject> obj2)
Method 3
[HttpGet("{obj1}/{obj2")]
public IActionResult Get(List<MyObject> obj1, List<MyObject> obj2)
Using FromQueryAttribute
I tried using:
[HttpGet]
public IActionResult Get([FromQueryAttribute] List<MyObject> obj1, [FromQueryAttribute] List<MyObject> obj2)
And it doesn't throw exception, but I don't know how to pass these parameters via query attribute?
Thanks in advance
p.s. I found How to pass multiple parameters to a get method in ASP.NET Core and Pass a list of complex object in query string to WEB API threads but didn't help me.
This seems like a slightly odd way to pass this data (why not just one long list of they are all the same object type?). Having said that, you first need to correct your attribute. The attribute is "[FromQuery]" which is from the "FromQueryAttribute" class. You don't include the "Attribute" part in the actual use of the attributes.
So the controller is:
[HttpGet]
public IActionResult Get([FromQuery] List<MyObject> obj1, [FromQuery] List<MyObject> obj2) {}
Then you need to form your query string paramaters to actually match this structure. The query string would look something like:
https://localhost:44315/api/test?obj1[0].Prop1=1&obj1[0].Prop2=2&obj2[0].Prop1=3&obj2[0].Prop2=4
This would create an obj1 parameter object in the Get method with one item in its list and that first item (zero index) has a Prop1 value of 1 and a Prop2 value of 2. It would also create an obj2 item one item in the list and a Prop1 value of 3 and a Prop2 value of 4.
If you wanted obj1 to have a second item in the list, then the index become 1 and you would add this to the query string:
...&obj1[1].Prop1=5&obj1[1].Prop2=6
I tested this on ASP.Net CORE 3.1 API and it worked fine.