如何将整数列表发送到Web API 2获取请求? [英] How to send a list of integers to web api 2 get request?

查看:152
本文介绍了如何将整数列表发送到Web API 2获取请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试完成此任务,我需要向Web api 2 get请求发送ID(整数)列表.

I am trying to accomplish this task in which I need to send a list of id's (integers) to a web api 2 get request.

所以我在此处,甚至有一个示例项目,但是它不起作用...

So I've found some samples here and it even has a sample project, but it doesn't work...

这是我的Web api方法代码:

Here is my web api method code:

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

这是我在提琴手中测试的URL:

and here is the URL which I test in fiddler:

http://192.168.9.43/api/NewHotelData/?ids=1,2,3,4

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

But the list is always empty and none of the id's are passing through to the method.

似乎无法理解问题是否出在方法中,URL中还是在这两者中...

can't seem to understand if the problem is in the method, in the URL or in both...

那么这怎么可能实现呢?

So how this is possible to accomplish ?

推荐答案

您将需要自定义模型绑定程序才能正常工作.这是您可以开始使用的简化版本:

You'll need custom model binder to get this working. Here's simplified version you can start work with:

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}):

And use it this way (remove {ids} from route):

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

如果要保持{ids}路线,则应将客户端请求更改为:

If you want to keep {ids} in route, you should change client request to:

api/NewHotelData/1,2,3,4


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


Another option (without custom model binder) is changing get request to:

?ids=1&ids=2&ids=3

这篇关于如何将整数列表发送到Web API 2获取请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆