提问人:behnam rahmani 提问时间:11/13/2023 更新时间:11/15/2023 访问量:82
如何将 CSV 格式的 C# 数字列表绑定到控制器级属性?
How can I bind a list of numbers in C# in CSV format to a controller-level property?
问:
我有这个 URL:
https://api.example.com/copmare/data?entityType=car&ids=1,2,3
我想将该 CSV 绑定到我的代码中的 a。1,2,3
List<int>
我正在使用此代码,但它不起作用:
public class CompareController : Controller
{
[BindProperty(SupportsGet=true)]
public List<int> Ids { get; set; }
}
但它不起作用,并告诉我该值对该属性无效。
我该怎么办?
答:
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;
}
}
评论
[FromQuery] string entityType, [FromQuery] List<int> ids
public IActionResult YourAction([FromQuery] string entityType, [FromQuery] List<int> ids)
[FromQuery]
[BindProperty]