ano
ano

Reputation: 53

ASP.NET Web API - GET request with multiple arguments

What I'm trying to do is to have an api request like /api/calculator?1=7.00&2=9.99&3=5.50&4=45.76 etc. How my controller can grab the request data? The keys/codes of the query string are ints between 1 and 1000. In the query string they can be some of the 1000 codes, not necessarily all of them. The value part is doubles.

The one way I think would work is if I create a model object (ex StupidObject) with 1000 properties (should use properties named like p1, p2,..p1000 for codes now, as ints are not an allowed property name), decorated with ModelBinder. Then for the controller I could have something like GetCalcResult(StupidObject obj){...} But that doesn't seem like an elegant solution :)

I tried controllers like GetCalcResult([FromURI]Dictionary<int, double> dict){...} but dict is always null. Also without the [FromURI] I get an error. Also tried List<KeyValuePair<int, double>> as controller parameter with the same results.

Could anyone point me at the right direction or give me an working example?

Upvotes: 5

Views: 15927

Answers (1)

Darrel Miller
Darrel Miller

Reputation: 142252

One way is to avoid trying to pass the values in as a parameter and simply do

  var queryValues = Request.RequestUri.ParseQueryString();

in your action method. QueryValues will be NameValueCollection that you can iterate over to get access to your query parameters.

If you really want to use a parameter, having a parameter of type [FromUri]FormDataCollection might work.

Upvotes: 13

Related Questions