If I have an ApiController
which has a post method which consumes a model which has data annotations for validation, how do I customize the name displayed for the validation errors? I don't really want to override the entire error message, but I do need the property in the error to be something other than the name of the property on the model type.
I've tried things like DisplayNameAttribute and DisplayAttribute, but those don't seem to apply for this.
The best solution I found for this was based on the following: https://gist.github.com/benfoster/4016852
You have to create your own validator provider (as shown in link), and your own validator which will set up a
ValidationContext
with the proper displayName such thatvalidationContext.DisplayName = displayNameMappingFunction(metadata.GetDisplayName());
You then need to register the validator provider globally by using GlobalConfiguration.Services, or you need to create an
IControllerConfigurationAttribute
which will configure it just for one controller.You do
config.Services.Replace(typeof(ModelValidatorProvider), new CustomDisplayNameProvider()