我正在尝试完成此任务,我需要将 ID(整数)列表发送到 Web API 2 get 请求。
所以我找到了一些样本 here它甚至有一个示例项目,但它不起作用...
这是我的 web api 方法代码:
[HttpGet]
[Route("api/NewHotelData/{ids}")]
public HttpResponseMessage Get([FromUri] List<int> ids)
{
// ids.Count is 0
// ids is empty...
}
这是我在 fiddler 中测试的 URL:
http://192.168.9.43/api/NewHotelData/?ids=1,2,3,4
但列表始终为空,并且没有任何 id 传递给该方法。
似乎无法理解问题出在方法中、URL 中还是两者中...
那么这是如何实现的呢?
最佳答案
您需要自定义模型 Binder 才能使其正常工作。这是您可以开始工作的简化版本:
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
另一个选项(没有自定义模型 Binder )正在将获取请求更改为:
?ids=1&ids=2&ids=3
关于c# - 如何将整数列表发送到 web api 2 get 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38217534/