Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get query string variables in MVC 4's Request?

I'm guffawed here working on my first MVC 4 project with the Web Api variety.

In MVC 3 I could get a query string parameter like such:

var unicornName = Request.Query["unicornName"];

But in MVC 4, it looks like the Request went from a HttpRequestBase to a HttpRequestMessage and the Query parameter is no more. So, hmm, okay, how do I get them now. I found a couple examples on the web but they are absurd.

This fellow recommends splitting the RequestUri's query string by "&" and finding your param and pair. And this example shows calling a GetQueryNameValuePairs method on the new request object which returns a list of key value pairs , then doing some linq to find your key and value. It can't really be this backwards to get something so simple. Please tell me I'm missing something!

Note: I can understand it's going the way of model binding and I should be bringing in query string parameters via the action's method params, but there are still times when query string variables need to be plucked (easily?) from the Request, such as in a Filter.

like image 972
Levitikon Avatar asked Oct 17 '12 22:10

Levitikon


People also ask

How can get query string value in MVC controller?

Just specify externalstring parameter on your action method: public ActionResult Index(string externalstring) { // ... } Or you can use Request. QueryString property.

Can get requests have query parameters?

For GET requests, input can be specified only as query parameters, because a GET request cannot have a body. This example shows a GET request on the search resource, with two query parameters in the query string.


2 Answers

If the linq is really that troublesome, just wrap the result of your GetQueryNameValuePairs() in a dictionary:

var requestQuery = 
    list.ToDictionary((keyItem) => keyItem.Key, (valueItem) => valueItem.Value);

You can then get your string parameter just like you always have:

var unicornName = requestQuery["unicornName"];
like image 39
Robert Harvey Avatar answered Sep 27 '22 21:09

Robert Harvey


I think this may be what you are looking for,

  var queryValues = Request.RequestUri.ParseQueryString();

https://stackoverflow.com/a/11729619/6819

like image 146
Darrel Miller Avatar answered Sep 27 '22 21:09

Darrel Miller