7

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.

Blake Rivell
  • 10,899
  • 23
  • 93
  • 182

1 Answers1

6

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...
Rion Williams
  • 69,631
  • 35
  • 180
  • 307
  • Ok so what should my query string param look like and what should the param in my Action Method look like? Additionally does it have to be an array? Can I use list? – Blake Rivell Jul 07 '16 at 17:52
  • 1
    The comma-delimited string approach that you are using should work just fine or you could use the second approach that I provided (i.e. repeated querystring parameters). [Filip Woj has a blog post](http://www.strathweb.com/2013/04/asp-net-web-api-parameter-binding-part-1-understanding-binding-from-uri/) on this topic that goes into a bit more detail and even uses a custom binder to handle comma-delimited values. – Rion Williams Jul 07 '16 at 17:54
  • Do you know why if I don't pass the param at all the list is coming in as instantiated with a count of 0? I expect it to be null. – Blake Rivell Jul 07 '16 at 19:02
  • I have the param like: List productIds = null – Blake Rivell Jul 07 '16 at 19:08
  • 1
    Will `[FromUri]` help in transferring a lots of data, like list of 1000 items, will it not be cumbersome sending it – Mrinal Kamboj Jul 08 '16 at 05:31
  • 1
    This does not work for a comma separated list as described. – socketman Oct 08 '16 at 03:26