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

13,594

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...
Share:
13,594
Blake Rivell
Author by

Blake Rivell

I am a .NET developer who builds custom web applications for businesses. I have a very strong passion for what I do. My hobbies are video games and fitness.

Updated on July 06, 2022

Comments

  • Blake Rivell
    Blake Rivell almost 2 years

    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
    Blake Rivell almost 8 years
    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?
  • Rion Williams
    Rion Williams almost 8 years
    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 on this topic that goes into a bit more detail and even uses a custom binder to handle comma-delimited values.
  • Blake Rivell
    Blake Rivell almost 8 years
    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
    Blake Rivell almost 8 years
    I have the param like: List<int> productIds = null
  • Mrinal Kamboj
    Mrinal Kamboj almost 8 years
    Will [FromUri] help in transferring a lots of data, like list of 1000 items, will it not be cumbersome sending it
  • girlcode
    girlcode over 7 years
    This does not work for a comma separated list as described.