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

前端 未结 17 1732
孤独总比滥情好
孤独总比滥情好 2020-11-22 04:40

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:



        
17条回答
  •  不思量自难忘°
    2020-11-22 05:08

    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 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.

提交回复
热议问题