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?
The above web API example will compile without an error but when you execute HTTP GET request then it will respond with the following multiple actions found error. This is because you cannot have multiple action methods with same number of parameters with same type. Both action methods above do not include any parameters.
As per the Web API naming convention, action method that starts with a word "Get" will handle HTTP GET request. We can either name it only Get or with any suffix.
As mentioned, Web API controller can include multiple Get methods with different parameters and types. Let's add following action methods in StudentController to demonstrate how Web API handles multiple HTTP GET requests. Returns student whose id matches with the specified id. Returns list of students whose name matches with the specified name.
Pass the params in the query string. What is best way to pass multiple query parameters to a restful api? Defining the params in the route: api/controller/date1/date2 Using a POST that inherently lets me pass an object with params. Researching ODATA since the Web API (currently) supports it.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With