【问题标题】:How to pass int array (int[]) to a Get method in ASP.NET Core如何将 int 数组 (int[]) 传递给 ASP.NET Core 中的 Get 方法
【发布时间】:2018-07-25 19:56:42
【问题描述】:

如何在 ASP.NET Core 中将int[] 传递给HttpGet 方法? (不作为查询参数!)

我发现的每篇文章都谈到了查询参数,但查询参数不是必需的。

我想要这样的东西:

[HttpGet("List/{ids}")]
public async Task<ActionResult<ViewItemModel[]>> List(int[] ids)

但 id 是空数组。我用 url 调用控制器方法:http://localh.../List/2062,2063,2064.
Swagger (Swashbuckle) 调用方法一模一样。

我找到了this post,但它已有 5 年历史,不适用于 ASP.NET Core。

【问题讨论】:

  • 看看这个,看看它是否有帮助。可能需要像以前的版本一样进行一些小的调整,但它可以工作stackoverflow.com/a/37768858/5233410
  • 最后,您将需要一个自定义模型绑定器。
  • 不确定这是否重复。您提供的链接中接受的答案是完美的,我正在寻找。问题是它在 ASP.NET Core 中不起作用。在此之前,我会使用你的答案。
  • 好的,没问题。如果你卡住了,请联系我,我会看看我能在哪里提供帮助。

标签: c# asp.net-core asp.net-core-webapi


【解决方案1】:

所有功劳都或多或少归功于 Nkosi 的回答 here。

public class EnumerableBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (!typeof(IEnumerable<int>).IsAssignableFrom(bindingContext.ModelType))
            throw new OpPISException("Model is not assignable from IEnumerable<int>.");

        var val = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (val == null)
            throw new NullReferenceException();

        var ids = val.Values.FirstOrDefault();
        if (ids == null)
            throw new NullReferenceException();

        var tokens = ids.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
        if (tokens.Length > 0)
        {
            try 
            {
                var clientsId = tokens.Select(int.Parse);
                object model = null;
                if (bindingContext.ModelType.IsArray)
                {
                    model = clientsId.ToArray();
                }
                else if (bindingContext.ModelType == typeof(HashSet<int>))
                {
                    model = clientsId.ToHashSet();
                }
                else
                {
                    model = clientsId.ToList();
                }                        
                bindingContext.ModelState.SetModelValue(bindingContext.ModelName, model);
                bindingContext.Result = ModelBindingResult.Success(model);
                return Task.CompletedTask;
            }
            catch {
                //...
            }
        }

        //If we reach this far something went wrong
        bindingContext.ModelState.TryAddModelError(bindingContext.ModelName, "Cannot convert.");
        bindingContext.Result = ModelBindingResult.Failed();
        return Task.CompletedTask;
    }
}

用例:

[HttpGet("List/{ids}")]
public async Task<ActionResult<ViewItemModel[]>> List([ModelBinder(typeof(EnumerableBinder))]HashSet<int> ids)
{
    //code
}

稍加思考后,可以将其更改为也使用其他类型,然后是 int。

【讨论】:

  • 做了一些小的重构。
猜你喜欢
  • 2014-06-03
  • 2020-08-23
  • 2016-07-16
  • 2021-06-28
  • 1970-01-01
  • 2019-01-29
  • 2018-12-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多