10

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.

3
  • 3
    What's wrong with working with a list of Key/Value pairs? Sounds pretty reasonable to me. Commented Oct 17, 2012 at 22:32
  • 1
    Wow.. I guess I didn't miss anything. It's a matter of regression I guess. What would you rather use, request["blah"] or request.GetQueryNameValuePairs().ToDictionary(e => e.Key, e => e.Value)["blah"]? Commented Oct 18, 2012 at 14:13
  • 2
    It seems Request.QueryString["query-string-name"] is back in MVC 5, just tried it myself and everything worked like a charm. Commented Nov 14, 2013 at 2:57

2 Answers 2

25

I think this may be what you are looking for,

  var queryValues = Request.RequestUri.ParseQueryString();

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

Sign up to request clarification or add additional context in comments.

Comments

5

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"];

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.