I have an ASP.NET Web API (version 4) REST service where I need to pass an array of integers.
Here is my action method:
public IEnumerable<Category> GetCategories(int[] categoryIds){ // code to retrieve categories from database }   And this is the URL that I have tried:
/Categories?categoryids=1,2,3,4 
                Arrays can be passed as arguments to method parameters. Because arrays are reference types, the method can change the value of the elements.
[FromQuery] - Gets values from the query string. [FromRoute] - Gets values from route data.
You just need to add [FromUri] before parameter, looks like:
GetCategories([FromUri] int[] categoryIds)   And send request:
/Categories?categoryids=1&categoryids=2&categoryids=3  
                        As Filip W points out, you might have to resort to a custom model binder like this (modified to bind to actual type of param):
public IEnumerable<Category> GetCategories([ModelBinder(typeof(CommaDelimitedArrayModelBinder))]long[] categoryIds)  {     // do your thing }  public class CommaDelimitedArrayModelBinder : IModelBinder {     public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)     {         var key = bindingContext.ModelName;         var val = bindingContext.ValueProvider.GetValue(key);         if (val != null)         {             var s = val.AttemptedValue;             if (s != null)             {                 var elementType = bindingContext.ModelType.GetElementType();                 var converter = TypeDescriptor.GetConverter(elementType);                 var values = Array.ConvertAll(s.Split(new[] { ","},StringSplitOptions.RemoveEmptyEntries),                     x => { return converter.ConvertFromString(x != null ? x.Trim() : x); });                  var typedValues = Array.CreateInstance(elementType, values.Length);                  values.CopyTo(typedValues, 0);                  bindingContext.Model = typedValues;             }             else             {                 // change this line to null if you prefer nulls to empty arrays                  bindingContext.Model = Array.CreateInstance(bindingContext.ModelType.GetElementType(), 0);             }             return true;         }         return false;     } }   And then you can say:
/Categories?categoryids=1,2,3,4 and ASP.NET Web API will correctly bind your categoryIds array.
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