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

前端 未结 17 2006
孤独总比滥情好
孤独总比滥情好 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:20

    Instead of using a custom ModelBinder, you can also use a custom type with a TypeConverter.

    [TypeConverter(typeof(StrListConverter))]
    public class StrList : List
    {
        public StrList(IEnumerable collection) : base(collection) {}
    }
    
    public class StrListConverter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
        }
    
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            if (value == null)
                return null;
    
            if (value is string s)
            {
                if (string.IsNullOrEmpty(s))
                    return null;
                return new StrList(s.Split(','));
            }
            return base.ConvertFrom(context, culture, value);
        }
    }
    

    The advantage is that it makes the Web API method's parameters very simple. You dont't even need to specify [FromUri].

    public IEnumerable GetCategories(StrList categoryIds) {
      // code to retrieve categories from database
    }
    

    This example is for a List of strings, but you could do categoryIds.Select(int.Parse) or simply write an IntList instead.

提交回复
热议问题