ASP.net core MVC 6 Data Annotations separation of problems

I want the Data Annotations attribute and the IClientValidatable interface in two separate assemblies to have a separation of concerns. One of them is called Common, and the other is Comman.Web.

These links explain how this works in MVC 5:

Saving IClientValidatable outside the model level

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 am using RC1.

+1
source share
2 answers

In Startup.cs in the ConfigureServices method:

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

You must customize your code when changing the ASP.NET Core 1.0 API. You can find an example implementation in the asp.net repository: DataAnnotationsModelValidatorProvider.cs

+1
source

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>(); 
0
source

All Articles