Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to pass a list of integer through web api or do I have to use a string param

I have a scenario where I need to send multiple ProductIds in a GET Request to my Web API.

In my asp.net web api controller is there a way that I can make the param of my Action method be of type List<int> productIds. I am assuming no, I have to pass them like this ?ProductIds=1,2,3 and then accept it as string productIds.

Please let me know if there is a better way.

like image 522
Blake Rivell Avatar asked Jul 07 '16 17:07

Blake Rivell


People also ask

What are the different ways to pass parameters in Web API?

Passing Data in your API Calls REST API endpoints can pass data within their requests through 4 types of parameters: Header, Path, Query String, or in the Request Body.

How do I pass multiple objects to Web API?

Best way to pass multiple complex object to webapi services is by using tuple other than dynamic, json string, custom class. No need to serialize and deserialize passing object while using tuple. If you want to send more than seven complex object create internal tuple object for last tuple argument.

What is parameter binding in Web API?

Binding is a process to set values for the parameters when Web API calls a controller action method. Web API methods with the different types of the parameters and how to customize the binding process.


1 Answers

You can indicate that you are going to be accepting an int[] as your parameter and Web API should handle mapping the comma-delimited string to an array as expected. You may need to include the [FromUri] attribute to let Web API know that you are expecting these values from the querystring :

public IEnumerable<Product> GetProducts([FromUri] int[] ProductIds)
{
      // Your code here.
}

You could also indicate that multiple values are mapped to the same querystring parameter via :

?ProductIds=1&ProductIds=2&ProductIds=3...
like image 106
Rion Williams Avatar answered Oct 21 '22 05:10

Rion Williams