I'm building one RESTful API using ASP.NET Core MVC and I want to use querystring parameters to specify filtering and paging on a resource that returns a collection.
In that case, I need to read the values passed in the querystring to filter and select the results to return.
I've already found out that inside the controller Get
action accessing HttpContext.Request.Query
returns one IQueryCollection
.
The problem is that I don't know how it is used to retrieve the values. In truth, I thought the way to do was by using, for example
string page = HttpContext.Request.Query["page"]
The problem is that HttpContext.Request.Query["page"]
doesn't return a string, but a StringValues
.
Anyway, how does one use the IQueryCollection
to actually read the querystring values?
You can just create an object like this:
And then in controller just make something like that:
Even better, you can create API model from:
to:
IQueryCollection
has aTryGetValue()
on it that returns a value with the given key. So, if you had a query parameter calledsomeInt
, you could use it like so:Notice that unless you have multiple parameters of the same name, the
StringValues
type is not an issue.You can use
[FromQuery]
to bind a particular model to the querystring:https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding
e.g.
ASP.NET Core will automatically bind
form values
,route values
andquery strings
by name. This means you can simply do this:Source: How model binding works
FYI, you can also combine the automatic and explicit approaches: