Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass an array of integers to ASP.NET Web API?

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 
like image 898
Hemanshu Bhojak Avatar asked Apr 02 '12 17:04

Hemanshu Bhojak


People also ask

Can you pass an array to a method C#?

Arrays can be passed as arguments to method parameters. Because arrays are reference types, the method can change the value of the elements.

What is FromQuery?

[FromQuery] - Gets values from the query string. [FromRoute] - Gets values from route data.


2 Answers

You just need to add [FromUri] before parameter, looks like:

GetCategories([FromUri] int[] categoryIds) 

And send request:

/Categories?categoryids=1&categoryids=2&categoryids=3  
like image 67
Lavel Avatar answered Sep 25 '22 17:09

Lavel


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.

like image 35
Mrchief Avatar answered Sep 23 '22 17:09

Mrchief