ASP.net core MVC 6 Data Annotations separation of concerns

这一生的挚爱 提交于 2019-12-06 19:54:30

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

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