Override existing data annotation attribute in asp.net core 1.1

I am trying to undo RequiresAttribute in a .net core and does not seem to work on asp.net core 1.1

Here is the test code

public class CustomRequiredAttribute : RequiredAttribute { public CustomRequiredAttribute():base() { } public override string FormatErrorMessage(string name) { return base.FormatErrorMessage(name); } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { return base.IsValid(value, validationContext); } } 

As soon as I use my model, I expect a normal result, such as "field required", since I have not configured it yet and just called the basic methods.

This does not work as expected, and will simply cost both the client side and the server side.

The purpose of this is to add a validation message output from db to the ErrorMessage property.

Any suggestions would be appreciated.

+6
source share
1 answer

Your problem is that ValidationAttributeAdapterProvider , which is the default implementation of IValidationAttributeAdapterProvider by default, only checks certain types. Thus, the use of custom implementations leads to the absence of "adapter providers", which leads to the absence of data attributes.

Decision. Provide your own implementation of IValidationAttributeAdapterProvider , which can redirect to the default implementation for non-standard materials ...

 public class CustomValidationAttributeAdapterProvider : IValidationAttributeAdapterProvider { private IValidationAttributeAdapterProvider innerProvider = new ValidationAttributeAdapterProvider(); public IAttributeAdapter GetAttributeAdapter(ValidationAttribute attribute, IStringLocalizer stringLocalizer) { if (attribute == null) throw new ArgumentNullException(nameof(attribute)); var type = attribute.GetType(); if (type == typeof(CustomRequiredAttribute)) return new RequiredAttributeAdapter((RequiredAttribute)attribute, stringLocalizer); return innerProvider.GetAttributeAdapter(attribute, stringLocalizer); } } 

... and register it as a single.

 services.AddSingleton<IValidationAttributeAdapterProvider, CustomValidationAttributeAdapterProvider>(); 
+2
source

Source: https://habr.com/ru/post/1013451/


All Articles