18

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.

1
  • You 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. Commented Jun 23, 2015 at 6:44

2 Answers 2

29

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)
{
    ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

[FromQuery] is what I was missing
This 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.
17

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.