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.
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.
To pass in parameter values, simply append them to the query string at the end of the base URL. In the above example, the view parameter script name is viewParameter1.
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)
{
...
}
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]);
}
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