【问题标题】:.NET core custom and default binding combined.NET 核心自定义和默认绑定相结合
【发布时间】:2021-08-27 23:42:48
【问题描述】:

我正在为视图模型创建自定义模型绑定器,实现 IModelBinder

我的视图模型中有很多属性,其中大部分不需要任何自定义绑定。与其从ModelBindingContext 单独显式设置我的模型上的所有属性值,不如让框架为我绑定模型,然后我将执行任何自定义绑定:

public class ApplicationViewModelBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
        {
            throw new ArgumentNullException(nameof(bindingContext));
        }

        // get .net core to bind values on model

        // Cary out any customization of the models properties

        bindingContext.Result = ModelBindingResult.Success(bindingContext.Model);
        return Task.CompletedTask; 
    }
}

基本上我想执行默认模型绑定,然后应用自定义绑定,类似于此 SO post 中采用的方法,但适用于 .NET Core,而不是框架。

我认为应用默认绑定会很简单,但一直无法找到如何做到这一点。我相信解决方案将涉及ComplexTypeModelBinderComplexTypeModelBinderProvider 类,但似乎无法找到解决方法。

我知道当 POST 请求到达我的控制器方法时我可以进行任何更改,但这似乎是错误的地方和错误的时间。

【问题讨论】:

    标签: asp.net-core asp.net-core-mvc model-binding custom-model-binder defaultmodelbinder


    【解决方案1】:

    对于自定义ComplexTypeModelBinder,您可以从ComplexTypeModelBinder 继承。

    1. 型号
        public class BinderModel
        {
           public int Id { get; set; }
           public string Name { get; set; }
           public string BinderValue { get; set; }
        }
    
    1. 控制器动作
        [HttpPost]
        public void Post([FromForm]BinderModel value)
        {
    
        }
    
    1. 自定义绑定器
        public class CustomBinder : ComplexTypeModelBinder
        {
            private readonly IDictionary<ModelMetadata, IModelBinder> _propertyBinders;
            public CustomBinder(IDictionary<ModelMetadata, IModelBinder> propertyBinders)
            : base(propertyBinders)
            {
                _propertyBinders = propertyBinders;
            }
            protected override Task BindProperty(ModelBindingContext bindingContext)
            {
                if (bindingContext.FieldName == "BinderValue")
                {
                    bindingContext.Result = ModelBindingResult.Success("BinderValueTest");
                    return Task.CompletedTask;
                }
                else
                {
                    return base.BindProperty(bindingContext);
                }
            }
            protected override void SetProperty(ModelBindingContext bindingContext, string modelName, ModelMetadata propertyMetadata, ModelBindingResult result)
            {
                base.SetProperty(bindingContext, modelName, propertyMetadata, result);
            }
        }
    
    1. CustomBinderProvider
        public class CustomBinderProvider : IModelBinderProvider
        {
            public IModelBinder GetBinder(ModelBinderProviderContext context)
            {
                if (context == null)
                {
                    throw new ArgumentNullException(nameof(context));
                }
    
                if (context.Metadata.IsComplexType && !context.Metadata.IsCollectionType)
                {
                    var propertyBinders = new Dictionary<ModelMetadata, IModelBinder>();
                    for (var i = 0; i < context.Metadata.Properties.Count; i++)
                    {
                        var property = context.Metadata.Properties[i];
                        propertyBinders.Add(property, context.CreateBinder(property));
                    }
    
                    //var loggerFactory = context.Services.GetRequiredService<ILoggerFactory>();
                    //return new ComplexTypeModelBinder(propertyBinders, loggerFactory);
                    return new CustomBinder(propertyBinders);
                }
    
                return null;
            }
    
        }
    
    1. 注入提供程序
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(options => {
                options.ModelBinderProviders.Insert(0, new CustomBinderProvider());
            });
        }
    

    【讨论】:

    • ComplexTypeModelBinder 没有单参数构造函数。 IModelBinder 为我工作。
    猜你喜欢
    • 2018-10-13
    • 2022-12-16
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 2016-03-27
    • 2018-08-22
    • 2019-11-14
    • 2018-01-20
    相关资源
    最近更新 更多