【问题标题】:ASP.net core MVC 6 Data Annotations separation of concernsASP.net core MVC 6 Data Annotations 关注点分离
【发布时间】:2016-04-18 11:26:00
【问题描述】:

我想将数据注释属性和IClientValidatable 接口放在两个单独的程序集中以分离关注点。一个叫做 Common,另一个叫做 Comman.Web。

这些链接解释了它在 MVC 5 中的工作原理:

Keeping IClientValidatable outside the model layer

http://www.eidias.com/blog/2012/5/25/mvc-custom-validator-with-client-side-validation

不幸的是,在 MVC 6 中没有

DataAnnotationsModelValidatorProvider.RegisterAdapter(
    typeof(MyValidationAttribute), 
    typeof(MyValidationAttributeAdapter)
);

它在 ASP.net 核心 MVC 6 中是如何工作的?我用的是 RC1。

【问题讨论】:

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


    【解决方案1】:

    在Startup.cs 中,在ConfigureServices 方法中:

    services.AddMvc(options =>
    {
        options.ModelValidatorProviders.Insert(0, new CustomModelValidatorProvider());
    });
    

    随着 ASP.NET Core 1.0 API 的更改,您必须调整您的代码。您可以在 asp.net 存储库中找到示例实现:DataAnnotationsModelValidatorProvider.cs

    【讨论】:

    • 非常感谢您的回复。在您的示例中,您使用IModelValidatorProvider。但我想注册一个IValidationAttributeAdapterProvider,就像这里:ValidationAttributeAdapterProvider.cs。
    • 在 ASP.net core RC2 中有什么想法吗?
    【解决方案2】:

    在 ASP.net core 1.0 中,我可以通过替换 IValidationAttributeAdapterProvider 服务来做到这一点。

    public class CustomValidationAttributeAdapterProvider : IValidationAttributeAdapterProvider
    {
        public IValidationAttributeAdapterProvider internalImpl;
    
        public CustomValidationAttributeAdapterProvider()
        {
            internalImpl = new ValidationAttributeAdapterProvider();
        }
    
        public IAttributeAdapter GetAttributeAdapter(ValidationAttribute attribute, IStringLocalizer stringLocalizer)
        {
            IAttributeAdapter adapter = internalImpl.GetAttributeAdapter(attribute, stringLocalizer);
    
            if (adapter == null)
            {
                var type = attribute.GetType();
    
                if (type == typeof(CustomValidatorAttribute))
                {
                    adapter = new CustomNumberValidatorAdapter((CustomValidatorAttribute)attribute, stringLocalizer);
                }
            }
    
            return adapter;
        }
    }
    

    在启动配置服务中

    if (services.Any(f => f.ServiceType == typeof(IValidationAttributeAdapterProvider)))
    {
        services.Remove(services.Single(f => f.ServiceType == typeof(IValidationAttributeAdapterProvider)));
    }
    services.AddScoped<IValidationAttributeAdapterProvider, CustomValidationAttributeAdapterProvider>();
    

    【讨论】:

    • 非常感谢。这样可行。你知道IModelValidatorProvider 是干什么用的吗?
    • 我首先查看了 IModelValidatorProvider,但我不确定它是如何工作的。我能够注册自己的 IModelValidatorProvider 实现,但是每当调用 CreateValidators 时,就没有 ValidatorItems 所以我真的无能为力。
    猜你喜欢
    • 2015-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-20
    • 2016-06-01
    • 1970-01-01
    • 2015-12-12
    相关资源
    最近更新 更多