ASP.NET Core 3.x RESTful API学习记录--自定义模型绑定
public class ArrayModelBinder: IModelBinder { /// <summary> /// bindingContext model的源数据 /// </summary> /// <param name="bindingContext"></param> /// <returns></returns> public Task BindModelAsync(ModelBindingContext bindingContext) { if (!bindingContext.ModelMetadata.IsEnumerableType) { bindingContext.Result = ModelBindingResult.Failed();//返回失败 return Task.CompletedTask; } var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).ToString(); if (string.IsNullOrWhiteSpace(value)) { bindingContext.Result = ModelBindingResult.Success(null); return Task.CompletedTask; } var elementType = bindingContext.ModelType.GetTypeInfo().GenericTypeArguments[0]; var converter = TypeDescriptor.GetConverter(elementType);//转换器 var values = value.Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries) .Select(x => converter.ConvertFromString(x.Trim())).ToArray(); var typedValues = Array.CreateInstance(elementType, values.Length); values.CopyTo(typedValues, 0); bindingContext.Model = typedValues; bindingContext.Result = ModelBindingResult.Success(bindingContext.Model); return Task.CompletedTask; } }
官方文档 https://docs.microsoft.com/zh-cn/aspnet/core/mvc/advanced/custom-model-binding?view=aspnetcore-3.1
知识来源草根专栏 感谢杨旭大佬