Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read values from the querystring with ASP.NET Core?

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?

like image 968
user1620696 Avatar asked Jan 10 '17 20:01

user1620696


People also ask

How can get query string parameter in asp net?

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.


1 Answers

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) {...} 
like image 168
Mike_G Avatar answered Sep 26 '22 00:09

Mike_G