您需要自定义模型绑定器才能使其正常工作。这是您可以开始使用的简化版本:
public class CsvIntModelBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
var key = bindingContext.ModelName;
var valueProviderResult = bindingContext.ValueProvider.GetValue(key);
if (valueProviderResult == null)
{
return false;
}
var attemptedValue = valueProviderResult.AttemptedValue;
if (attemptedValue != null)
{
var list = attemptedValue.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries).
Select(v => int.Parse(v.Trim())).ToList();
bindingContext.Model = list;
}
else
{
bindingContext.Model = new List<int>();
}
return true;
}
}
并以这种方式使用它({ids}
从路线中删除):
[HttpGet]
[Route("api/NewHotelData")]
public HttpResponseMessage Get([ModelBinder(typeof(CsvIntModelBinder))] List<int> ids)
如果您想保持{ids}
路线,您应该将客户端请求更改为:
api/NewHotelData/1,2,3,4
另一种选择(没有自定义模型绑定器)是将获取请求更改为:
?ids=1&ids=2&ids=3