Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing querystring in ASP.NET MVC6

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.

like image 686
Web Dev Avatar asked Jun 23 '15 06:06

Web Dev


People also ask

What is request QueryString 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.

How do you pass a value in QueryString?

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.


2 Answers

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)
{
    ...
}
like image 115
Yishai Galatzer Avatar answered Nov 19 '22 08:11

Yishai Galatzer


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

enter image description here

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]);
 }

enter image description here

like image 40
ramiramilu Avatar answered Nov 19 '22 07:11

ramiramilu