2

I'm working on an API, and I wanted to try and get sort, filter, and pagination objects through my query string in JSON form.

Currently, I'm calling my API with this:

baseUrl/reviews?sort={"direction":"asc","field":"time"}&filters=[{"field":"rating","value":9}]&page={"page":1,"items":10}

And my controller looks like:

namespace NewApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ApiController : ControllerBase
    {
        [HttpGet]
        public JsonResult Search([FromQuery(Name = "sort")] Sort sort, [FromQuery(Name = "Filters")] List<Filter> filters, [FromQuery(Name = "Page")] Page page)
        {
            ... getting data from db be here ..
        }
    }
}

With this, all my parameters are null.

I saw other questions similar to this that talked about custom model binding. I've tried that, but I couldn't get the values from the query string in order to try deserializing the JSON data.

Another workaround answer I saw was to just pass one JSON object and deserialize it in the controller. But I still wasn't able to get any data out of the query string.

1 Answer 1

2

What you're trying to do with non-primitive objects has to be done using the body of http request. If you want to do it in a query string stick to primitives.

baseUrl/reviews?sortDirection=asc&sortField=time&filterField=rating&filterValue=9&page=1&items=10


[Route("api/[controller]")]
[ApiController]
public class ApiController : ControllerBase
{
    [HttpGet]
    public JsonResult Search(string sortDirection, string sortField, string filterField, string filterValue, int page, int items)
    // I would also recommend returning IHttpActionResult, much more robust
    {
        ... getting data from db be here ..
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.