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?
StringValues
is an array of strings. You can get your string value by providing an index, e.g.HttpContext.Request.Query["page"][0]
.I have a better solution for this problem,
var searchparams = await Request.GetSearchParams();
I have created a static class with few extension methods
in this way you can easily access all your search parameters. I hope this will help many developers :)
You could use the ToString method on
IQueryCollection
which will return the desired value if a singlepage
parameter is specified:if there are multiple values like
?page=1&page=2
then the result of the ToString call will be1,2
But as @mike-g suggested in his answer you would better use model binding and not directly accessing the
HttpContext.Request.Query
object.in .net core if you want to access querystring in our view use it like
if we are in location where @Context is not avilable we can inject it like
also for cookies
Here is a code sample I've used (with a .NET Core view):
Some of the comments mention this as well, but asp net core does all this work for you.
If you have a query string that matches the name it will be available in the controller.
https://myapi/some-endpoint/123?someQueryString=YayThisWorks
Ouputs:
123
YayThisWorks