Accessing querystring in ASP.NET MVC6
Solution 1
Getting query with an indexer is supported.
See MVC code test here - https://github.com/aspnet/Mvc/blob/e0b8532735997c439e11fff68dd342d5af59f05f/test/WebSites/ControllersFromServicesClassLibrary/QueryValueService.cs
context.Request.Query["value"];
Also note that in MVC 6 you can model bind directly from query by using the [FromQuery] attribute.
public IActionResult ActionMethod([FromQuery]string key1)
{
...
}
Solution 2
So, my question is - how do I access query string parameters in MVC6?
You can use Request.Query
which is new addition in ASPNET 5.
var queryStrings = Request.Query;
The URL I am going to try was - http://localhost:12048/Home/Index?p=123&q=456
And you can get All Keys using -
queryStrings.Keys
And then you can get the values by iterating keys -
var qsList = new List<string>();
foreach(var key in queryStrings.Keys)
{
qsList.Add(queryStrings[key]);
}
Related videos on Youtube
Web Dev
Updated on September 15, 2022Comments
-
Web Dev over 1 year
I am trying to access query string parameters in my ASP.NET MVC6 applications. But it seems unlike MVC5 and web forms, QueryString doesn't have any indexer and I can't say something like:
string s = Request.QueryString["key1"] //gives error
So, my question is - how do I access query string parameters in MVC6?
Surprisingly
Request.Forms
collection works as expected (as in MVC5 or web forms).Thank you.
-
Akash Kava almost 9 yearsYou are not supposed to use QueryString or Form in MVC, instead you should have parameter in your controller that will automatically bind to the values.
-
-
galdin over 7 years
[FromQuery]
is what I was missing -
Michael Silver almost 7 yearsThis is actually a learning moment. I had no idea [FromQuery] even existed. It doesn't seem to be well documented. There is also a [FromHeader] and [FromForm] among others. You can even write custom binders, as well.