.net core webapi 接收 (1,2,4) 格式的数组参数

 

引用命名空间 

Microsoft.AspNetCore.Mvc.ModelBinding

 1   public class ArrayModelBinder : IModelBinder
 2     {
 3         public Task BindModelAsync(ModelBindingContext bindingContext)
 4         {
 5             // Our binder works only on enumerable types
 6             if (!bindingContext.ModelMetadata.IsEnumerableType)
 7             {
 8                 bindingContext.Result = ModelBindingResult.Failed();
 9                 return Task.CompletedTask;
10             }
11 
12             // Get the inputted value through the value provider
13             var value = bindingContext.ValueProvider
14                 .GetValue(bindingContext.ModelName).ToString();
15 
16             // If that value is null or whitespace, we return null
17             if (string.IsNullOrWhiteSpace(value))
18             {
19                 bindingContext.Result = ModelBindingResult.Success(null);
20                 return Task.CompletedTask;
21             }
22 
23             // The value isn't null or whitespace, 
24             // and the type of the model is enumerable. 
25             // Get the enumerable's type, and a converter 
26             var elementType = bindingContext.ModelType.GetTypeInfo().GenericTypeArguments[0];
27             var converter = TypeDescriptor.GetConverter(elementType);
28 
29             // Convert each item in the value list to the enumerable type
30             var values = value.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)
31                 .Select(x => converter.ConvertFromString(x.Trim()))
32                 .ToArray();
33 
34             // Create an array of that type, and set it as the Model value 
35             var typedValues = Array.CreateInstance(elementType, values.Length);
36             values.CopyTo(typedValues, 0);
37             bindingContext.Model = typedValues;
38 
39             // return a successful result, passing in the Model 
40             bindingContext.Result = ModelBindingResult.Success(bindingContext.Model);
41             return Task.CompletedTask;
42         }
43     }

使用 

 1  /// <summary>
 2         /// 批量删除
 3         /// </summary>
 4         /// <returns></returns>
 5         [HttpDelete("({touristIDs})")]
 6         public async Task<IActionResult> DeleteByIdsAsync(
 7             [ModelBinder(BinderType = typeof(ArrayModelBinder))]
 8             [FromRoute] IEnumerable<Guid> touristIDs)
 9         {
10             if (touristIDs == null)
11             {
12                 return BadRequest();
13             }
14             IEnumerable<TouristRoute> touristRoutes = await _touristRouteRepository.GetTouristRoutesByIDListAsync(touristIDs);
15             _touristRouteRepository.DeleteTouristRoutes(touristRoutes);
16             _touristRouteRepository.Save();
17             return NoContent();
18         }

测试

 

posted on 2023-05-06 16:33  是水饺不是水饺  阅读(284)  评论(0)    收藏  举报

导航