c# - 如何将 int 数组 (int[]) 传递给 ASP.NET Core 中的 Get 方法

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

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

我找到的每个帖子都在谈论查询参数,但查询参数不是必需的。

我想要这样的东西:

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

但 ids 是空数组。我使用 url 调用 Controller 方法:http://localh.../List/2062,2063,2064
招摇(Swashbuckle)调用方法完全一样。

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

最佳答案

所有功劳或多或少归功于 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 之外的其他类型。

关于c# - 如何将 int 数组 (int[]) 传递给 ASP.NET Core 中的 Get 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51516426/

相关文章:

c# - 跨线程问题

c# - Javascript 不适用于 ASP.NET 上的 Timer Tick 方法

c# - 从ASP.Net Core中的wwwroot/images获取图像

c# - 为什么 Asp.net core Web API 2.0 返回 Http Error 500

c# - 记录器未显示在 ASP.NET Core 2.1 应用程序中

c# - .NET 核心 2.2 : Validate [required] properties only when object is not null

c# - using() { } block 中的 yield return 语句 在执行之前处理

c# - 从另一个线程使用 Unity API 或在主线程中调用函数

c# - 简单的 ASP.NET Core 路由问题

c# - 绕过 .Net Core 中的授权属性以获得发布版本