Possible to pass a list of integer through web api or do I have to use a string param
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...
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, 2022Comments
-
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 asstring productIds
.Please let me know if there is a better way.
-
Blake Rivell almost 8 yearsOk 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 almost 8 yearsThe 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 almost 8 yearsDo 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 almost 8 yearsI have the param like: List<int> productIds = null
-
Mrinal Kamboj almost 8 yearsWill
[FromUri]
help in transferring a lots of data, like list of 1000 items, will it not be cumbersome sending it -
girlcode over 7 yearsThis does not work for a comma separated list as described.