Reputation: 460238
I'm using ASP.NET Core 6.0 and i need to create an api endpoint that can handle two fix parameters that must be provided always and a list of optional filter parameters:
https://<host>/api/article/GetArticles?pageId=123&filterId=234&filter[category]=1,2&filter[author]=12&filter[year]=2023
as you can see the filter-types are specified in brackets. This is the filter standard defined in JSON:API which should be used. But how does the endpoint in the controller needs to be defined to support it?
This does not work, of course(filter
is null
):
[HttpGet("GetArticles")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<IContent>> GetArticles(
int pageId,
int filterId,
string? filter = null)
{
// TODO ...
return Ok();
}
Upvotes: 3
Views: 1061
Reputation: 143033
You can use dictionary for such mapping - [FromQuery] Dictionary<string, string>? filter = null
:
[HttpGet("GetArticles")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult> GetArticles(
int pageId,
int filterId,
[FromQuery] Dictionary<string, string>? filter = null)
{
// TODO ...
return Ok();
}
Upvotes: 4
Reputation: 575
This is a minimal working example. Tested with this path in the Postman
/GetArticles?pageId=1&filterId=2&filter[category]=3&filter[author]=5
Notice that filter is dictionary because I'm sending key value pairs for filter property
[HttpGet("GetArticles")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<IContent>> GetArticles(
int pageId,
int filterId,
[FromQuery] IDictionary<string, string>? filter)
{
// TODO ...
return Ok();
}
I think you can imagine now that you can do more than this.
Upvotes: 3