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?
A Query String collection is a parsed version of the QUERY_STRING variable in the Server Variables collection. It enable us to retrieve the QUERY_STRING variable by name. When we use parameters with Request. QueryString, the server parses the parameters sent to the request and returns the effective or specified data.
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.
[HttpGet()] public IActionResult Get([FromQuery(Name = "page")] string page) {...}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With