Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get GET parameters with ASP.NET MVC ApiController

I feel a bit absurd asking this but I can't find a way to get parameters for a get request at /api/foo?sort=name for instance.

In the ApiController class, I gave a public string Get(). Putting Get(string sort) makes /api/foo a bad request. Request instance in the ApiController is of type System.Net.Http.HttpRequestMessage. It doesn't have a QueryString or Parameters property or anything.

like image 330
xster Avatar asked May 18 '12 17:05

xster


1 Answers

The ApiController is designed to work without the HttpContext object (making it portable, and allowing it to be hosted outside of IIS).

You can still access the query string parameters, but it is done through the following property:

Request.GetQueryNameValuePairs() 

Here's an example loop through all the values:

foreach (var parameter in Request.GetQueryNameValuePairs()) {      var key = parameter.Key;      var value = parameter.Value; } 
like image 146
Darren Avatar answered Sep 18 '22 12:09

Darren