如何向web api 2获取请求发送整数列表?

Lir*_*man 6 c# get-request asp.net-web-api2

我正在尝试完成此任务,我需要将一个id(整数)列表发送到web api 2 get请求.

所以我在这里找到了一些样品,它甚至有一个示例项目,但它不起作用......

这是我的web api方法代码:

[HttpGet]
[Route("api/NewHotelData/{ids}")]
public HttpResponseMessage Get([FromUri] List<int> ids)
{
    // ids.Count is 0
    // ids is empty...
}
Run Code Online (Sandbox Code Playgroud)

这是我在fiddler中测试的URL:

http://192.168.9.43/api/NewHotelData/?ids=1,2,3,4
Run Code Online (Sandbox Code Playgroud)

但是列表始终为空,并且没有任何id传递给该方法.

似乎无法理解问题出在方法,URL或两者中......

那怎么可能实现呢?

Ale*_* L. 11

您需要自定义模型绑定器才能实现此功能.这是您可以开始使用的简化版本:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

并以这种方式使用它({ids}从路线中删除):

[HttpGet]
[Route("api/NewHotelData")]
public HttpResponseMessage Get([ModelBinder(typeof(CsvIntModelBinder))] List<int> ids)
Run Code Online (Sandbox Code Playgroud)

如果您想保留{ids}路线,则应将客户请求更改为:

api/NewHotelData/1,2,3,4
Run Code Online (Sandbox Code Playgroud)

另一个选项(没有自定义模型绑定器)将get请求更改为:

?ids=1&ids=2&ids=3
Run Code Online (Sandbox Code Playgroud)


Hon*_*fus 6

按照注释中的建议使用自定义模型活页夹是执行此操作的正确方法。但是,您也可以像这样快速简便地执行此操作:

[HttpGet]
[Route("api/NewHotelData")]
public HttpResponseMessage Get([FromUri] string ids)
{
    var separated = ids.Split(new char[] { ',' });
    List<int> parsed = separated.Select(s => int.Parse(s)).ToList();
}
Run Code Online (Sandbox Code Playgroud)

首先,我分割uri ids字符串,然后使用Linq将它们转换为整数列表。请注意,这缺少完整性检查,如果参数的格式错误,则会引发期望。

您这样称呼它: http://192.168.9.43/api/NewHotelData?ids=5,10,20

更新:就我个人而言,我认为将模型绑定器用于诸如此类的简单事情是过度设计的。您需要很多代码才能使事情变得简单。实际上,在模型绑定程序中使用的代码非常相似,您将获得更好的method参数语法。如果将整数分析包装到try-catch块中,并在格式错误的情况下返回适当的错误消息,我看不出为什么不使用这种方法的原因。