ASP.net core MVC 6 Data Annotations separation of concerns

扶醉桌前 提交于 2019-12-08 07:04:46

问题


I want put the Data Annotations Attribute and the IClientValidatable interface in two seperate assemblies to have separation of concerns. One is called Common and the other Comman.Web.

These links explain how it works in MVC 5:

Keeping IClientValidatable outside the model layer

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

Unfortunately in MVC 6 there is no

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

How does it work in ASP.net core MVC 6? I use the RC1.


回答1:


In Startup.cs, in the ConfigureServices method:

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

You have to adjust your code as the ASP.NET Core 1.0 API is changed. You could find a sample implementation in the asp.net repo: DataAnnotationsModelValidatorProvider.cs




回答2:


In ASP.net core 1.0 I was able to do this by replacing the IValidationAttributeAdapterProvider service.

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;
    }
}

In Startup ConfigureServices

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


来源:https://stackoverflow.com/questions/36692627/asp-net-core-mvc-6-data-annotations-separation-of-concerns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!