zoukankan      html  css  js  c++  java
  • 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

    知识来源草根专栏 感谢杨旭大佬

  • 相关阅读:
    mirco新建proto流程
    Ubuntu默认防火墙安装、启用、配置、端口、查看状态相关信息
    Rails核心组件
    Ruby中文乱码问题
    python str转dict
    SQLserver AwaysOn日志文件过大,处理办法
    MySQL的一些小细节
    mysql删除表中重复值
    可恶的自增长标识符
    reset slave all更彻底
  • 原文地址:https://www.cnblogs.com/cqqinjie/p/13372158.html
Copyright © 2011-2022 走看看