將整數(shù)數(shù)組傳遞給ASP.NETWebAPI?我有一個ASP.NETWebAPI(Version 4)REST服務,在這里我需要傳遞一個整數(shù)數(shù)組。以下是我的行動方法:public IEnumerable<Category> GetCategories(int[] categoryIds){// code to retrieve categories from database}這是我嘗試過的網(wǎng)址:/Categories?categoryids=1,2,3,4
3 回答

素胚勾勒不出你
TA貢獻1827條經(jīng)驗 獲得超9個贊
[FromUri]
GetCategories([FromUri] int[] categoryIds)
/Categories?categoryids=1&categoryids=2&categoryids=3

DIEA
TA貢獻1820條經(jīng)驗 獲得超3個贊
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 關注
- 1307 瀏覽
添加回答
舉報
0/150
提交
取消