【问题标题】:Mixing Custom and Default Model Binding混合自定义和默认模型绑定
【发布时间】:2018-10-13 11:03:37
【问题描述】:

在默认模型绑定完成后,我需要运行一些代码来进一步绑定某个模型。我不想完全替换现有的模型绑定。

这个问题解释了这是如何在 pre-CORE ASP.NET 中完成的: ASP.NET MVC - Mixing Custom and Default Model Binding

但是,这种方法在 ASP.NET Core 中似乎不起作用,因为不再有 DefaultModelBinder 类。

在 ASP.NET Core 中可以使用哪些替代方案?

【问题讨论】:

标签: asp.net asp.net-mvc asp.net-core .net-core asp.net-core-mvc


【解决方案1】:

您可以利用ComplexTypeModelBinder 来完成实际工作,然后在完成后注入您自己的逻辑。

例如(假设您的自定义类型是MyCustomType):

public class MyCustomType
{
    public string Foo { get; set; }
}

public class MyCustomTypeModelBinder : IModelBinder
{
    private readonly IDictionary<ModelMetadata, IModelBinder> _propertyBinders;

    public MyCustomTypeModelBinder(IDictionary<ModelMetadata, IModelBinder> propertyBinders)
    {
        this._propertyBinders = propertyBinders;
    }

    public async Task BindModelAsync(ModelBindingContext bindingContext)
    {
        var complexTypeModelBinder = new ComplexTypeModelBinder(this._propertyBinders);

        // call complexTypeModelBinder
        await complexTypeModelBinder.BindModelAsync(bindingContext);

        var modelBound = bindingContext.Model as MyCustomType;

        // do your own magic here
        modelBound.Foo = "custominjected";
    }
}

public class MyCustomTypeModelBinderProvider : IModelBinderProvider
{
    public IModelBinder GetBinder(ModelBinderProviderContext context)
    {
        if (context.Metadata.ModelType == typeof(MyCustomType))
        {
            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));
            }

            return new MyCustomTypeModelBinder(propertyBinders);
        }

        return null;
    }
}

然后注册:

services.AddMvc(options =>
{
    options.ModelBinderProviders.Insert(0, new MyCustomTypeModelBinderProvider());
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-14
    • 1970-01-01
    • 2018-08-22
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-16
    相关资源
    最近更新 更多