混合自定义和默认模型绑定

时间:2018-05-03 08:00:39

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

在完成默认模型绑定后,我需要运行一些代码到进一步数据绑定某些模型。我不想完全取代现有的模型绑定。

此问题解释了如何在CORE之前的ASP.NET中完成此操作: ASP.NET MVC - Mixing Custom and Default Model Binding

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

ASP.NET Core中可以使用哪种替代方法?

1 个答案:

答案 0 :(得分:0)

您可以利用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());
});