2

I am developing a Web API with .NET Core 2.1 where the response is manipulated based on the output received from a WCF service.

I need to have a API with Get verb and need to pass an array of complex objects as the input to it.The challenge currently I am facing is, the array is not getting detected from the input.I have added [FromQuery] along with the input parameter. I am trying the same from Swagger UI.

Tried adding Name along with FromQuery .

[HttpGet("test")]
public IActionResult Testmethod([FromQuery] Person person)
{
    return Ok(person);
}

Model classes:

public class Person
{
    public string Name{ get; set; }
    public int Age{ get; set; }
    public Grade[] grades{ get; set; }
}

public class Grade
{
    public int GradeId { get; set; }
    public string GradeName { get; set; }
    public string Section { get; set; }
}
harvzor
  • 2,832
  • 1
  • 22
  • 40
ams16
  • 63
  • 7

2 Answers2

0

It seems that Swagger generates the query a little bit wrong for this case. The correct query is:

GET /test
  ?name=thomas
  &age=20
  &grade[0].gradeId=2
  &grade[0].gradeName=Second
  &grade[0].section=Section

External resources

This issue has been documented here: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1832

Also talked about here: OpenAPI query string parameter with list of objects

Solution

This is an issue with OpenAPI and we can not solve it.

This is the best solution:

If you are designing a new API (rather than describing an existing one), consider passing the array of objects in the request body instead.

https://stackoverflow.com/a/52894157

Query string format is different depending on the object

This is unusual because if the code was like this:

[HttpGet("test")]
public IActionResult Testmethod([FromQuery] SomeQuery query)
{
    // ...
}

public class SomeQuery
{
    public int[] Ids { get; set; }
}

Our API call will look like:

GET /test
  ?ids=1
  &ids=2

However, if you have an array of objects, then the format of the GET request changes.

Versions tested with

  • Swashbuckle.AspNetCore 6.5.0
  • .NET Framework net5.0
harvzor
  • 2,832
  • 1
  • 22
  • 40
-2

Try the below

[FromBody] IEnumerable<Person> persons
Hakit01
  • 91
  • 3
  • 8
  • From the question *I need to have a API with Get verb*. Also, what makes you think OP needs an enumerable of Person? – DavidG May 31 '19 at 13:19
  • The issue is with Grade[] object.Its coming as null in the request,Not the Person.. – ams16 May 31 '19 at 13:21