将整数数组传递给ASP.NETWebAPI?我有一个ASP.NETWebAPI(Version 4)REST服务,在这里我需要传递一个整数数组。以下是我的行动方法:public IEnumerable<Category> GetCategories(int[] categoryIds){// code to retrieve categories from database}这是我尝试过的网址:/Categories?categoryids=1,2,3,4
3 回答
素胚勾勒不出你
TA贡献1827条经验 获得超9个赞
[FromUri]
GetCategories([FromUri] int[] categoryIds)
/Categories?categoryids=1&categoryids=2&categoryids=3
DIEA
TA贡献1820条经验 获得超2个赞
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; }}
/Categories?categoryids=1,2,3,4
categoryIds
- 3 回答
- 0 关注
- 1261 浏览
添加回答
举报
0/150
提交
取消