Web Dev
Web Dev

Reputation: 735

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.

Upvotes: 18

Views: 18788

Answers (2)

ramiramilu
ramiramilu

Reputation: 17182

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

Upvotes: 17

Yishai Galatzer
Yishai Galatzer

Reputation: 8862

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)
{
    ...
}

Upvotes: 29

Related Questions