如何将 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/