Search code examples
c#asp.net-core-mvcasp.net-core-webapiasp.net-core-6.0json-api

How to pass multiple related parameters in GET request for "filter query parameter family" standards defined in in JSON:API?


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();
}

Solution

  • 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();
    }