如何将 CSV 格式的 C# 数字列表绑定到控制器级属性?

How can I bind a list of numbers in C# in CSV format to a controller-level property?

提问人:behnam rahmani 提问时间:11/13/2023 更新时间:11/15/2023 访问量:82

问:

我有这个 URL:

https://api.example.com/copmare/data?entityType=car&ids=1,2,3

我想将该 CSV 绑定到我的代码中的 a。1,2,3List<int>

我正在使用此代码,但它不起作用:


public class CompareController : Controller
{
    [BindProperty(SupportsGet=true)]
    public List<int> Ids { get; set; }
}

但它不起作用,并告诉我该值对该属性无效。

我该怎么办?

C# ASP.NET-Core HTTP 查询字符串

评论

0赞 Yong Shun 11/13/2023
您是否尝试过将参数添加到 API 操作中:?[FromQuery] string entityType, [FromQuery] List<int> idspublic IActionResult YourAction([FromQuery] string entityType, [FromQuery] List<int> ids)
0赞 behnam rahmani 11/13/2023
@YongShun,是否可以将其添加到?[FromQuery][BindProperty]
0赞 Yong Shun 11/13/2023
我测试了你的代码并工作了。您使用的是哪个 ASP.NET Core 版本?
0赞 behnam rahmani 11/15/2023
@YongShun,我正在使用 ASP.NET Core 最新的 LTS(我猜是当前时间为 7.0.14)。

答:

0赞 Yuning Duan 11/15/2023 #1

ASP.NET Core 的模型绑定器处理简单类型直接从查询字符串参数到相应类型的转换。但对于集合类型,模型绑定器不会直接将逗号分隔的字符串转换为 List<int>。您可以使用自定义模型绑定器将其转换为 List<int>。

控制器:

public class CompareController : ControllerBase
{
    [HttpGet("data")]
    public IActionResult GetData([FromQuery] string entityType, [ModelBinder(BinderType = typeof(MyModelBinder))] List<int> ids)
    {
          
        return Ok(new { EntityType = entityType, Ids = ids });
    }
}

我的模型绑定器:

public class MyModelBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
        {
            throw new ArgumentNullException(nameof(bindingContext));
        }

        var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        if (valueProviderResult != ValueProviderResult.None)
        {
            var values = valueProviderResult.FirstValue;

            if (!string.IsNullOrEmpty(values))
            {
                var ints = values.Split(',').Select(int.Parse).ToList();
                bindingContext.Result = ModelBindingResult.Success(ints);
                return Task.CompletedTask;
            }
        }

        return Task.CompletedTask;
    }
}

当我发送数据时:enter image description here