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