c# - 如何将整数列表发送到 web api 2 get 请求?

标签 c# asp.net-web-api2 get-request

我正在尝试完成此任务,我需要将 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/

相关文章:

c# - 使用XmlArray反序列化xml文件?

c# - 如何在不返回 asp.net View 的情况下验证表单?

c# - 亚马逊 S3 : How to get a list of folders in the bucket?

c# - Windows Phone 8.1 的 SQLite.Net PCL 支持/解决方法

asp.net-web-api - Web API 帮助页面始终为空

c# - 使用 C# ASP.NET WebAPI 2.0 在 InputModel 主体中绑定(bind) NodaTime Instant 字段

spring - 如何从 spring boot Controller 向另一台服务器执行 http 请求

python - 在Python中解析HTML数据

Azure 移动服务自定义 API 在客户端收到错误请求

html - NodeJS 请求对象在 GET 请求上为空