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.
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>();
来源:https://stackoverflow.com/questions/36692627/asp-net-core-mvc-6-data-annotations-separation-of-concerns