7

I have a complex object to be passed as query string in ASP.Net Core 3.2.

public class Customer
{
    public string Firstname { get; set; }
    public List<Address> Addresses { get; set; }
}

public class Address
{
    public string Home_Address { get; set; }
    public string Office_Address { get; set; }
}

It works in Postman as below:

http://localhost:52100/v1/Customer?Addresses[0].Home_Address=123HomeStreet&Addresses[0].Office_Address=123OfficeStreet

But, how to pass the value in Swagger documentation for Addresses which is of type "array[object] (query)" http://localhost:52100/v1/swagger-ui/index.html

I have Swashbuckle.AspNetCore 5.4.1, Swashbuckle.AspNetCore.Annotations 5.4.1, Swashbuckle.AspNetCore.Filters 5.1.1 references added in my project

Rakshitha
  • 91
  • 1
  • 6
  • Have you tried `[FromQuery]` attribute in your action? – Nilay Mehta Jun 16 '20 at 12:07
  • Yes, I have used as public async Task GetCustomer([FromQuery] Customer request) – Rakshitha Jun 16 '20 at 12:37
  • Yes, I verified it does not provide fields in the Swagger UI when Array/List within model exists. Looks like you need to create custom `OperationFilter` for this. – Nilay Mehta Jun 16 '20 at 13:12
  • can you provide some sample code on how to do this – Rakshitha Jun 16 '20 at 13:46
  • OpenAPI Specification does not support arrays of objects in the query string - see https://stackoverflow.com/q/52892768/113116. Consider sending this parameter in the request body instead. – Helen Jun 16 '20 at 14:11
  • Yes, Helen is right. I tried to do it on my example using custom OperationFilter. But unfortunately, it does not work as per expectation. It passes the below data, which means encode square brackets. `?Addresses%5B0%5D.Home_Address=123&Addresses%5B0%5D.Office_Address=123` – Nilay Mehta Jun 16 '20 at 14:23
  • Can you please provide some sample code how to send as parameter in request body a list of properties for the same. – Rakshitha Jun 16 '20 at 17:20
  • I had the same issue when passing List, however when it comes to List, it works. So probably it recognizes list of string rather than list of object. What i did was passing the object as json string from the frontend and then parse it as the object at the backend – samheihey Oct 24 '20 at 09:41
  • If you can change the OpenAPI definition, you can put JSON (urlencoded) into query. See https://stackoverflow.com/a/72315830/94148 – aleung May 20 '22 at 08:58

1 Answers1

0

"Get" requests are not the industry standard for such queries. And here is a list with N adresses, so you should use the "Post" request with parameter attribute [FromBody]

[HttpPost]
public async Task<ActionResult> PostAsync([FromBody] Customer customerObj, CancellationToken cancellationToken)
{
// your code
}

and Body:

{
  "FirstName": "John",
  "Adresses": [
    {
      "Address": {
        "Home_Address": "WorkDrive 11",
        "Office_Address": "HomeDrive 22"
      }
    }
  ]
}
K Paul
  • 1
  • 2