Web Api ModelState validation ignores DisplayAttribute

For a model with these data annotations:

public class Example { [Required] [Display(Name = "Activity response")] public string ActivityResponse { get; set; } } 

I expect the model status error message to be “Activity Response Field”. Instead, an “ActivityResponse Field" is required.

+7
source share
2 answers

There was the same problem, and I made a workaround for her. I know this is not perfect.

For each dataannotation attribute, create a new class

 public class RequiredAttribute : System.ComponentModel.DataAnnotations.RequiredAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { validationContext.DisplayName = ModelMetadataProviders .Current .GetMetadataForProperty(null, validationContext.ObjectType, validationContext.DisplayName) .DisplayName; return base.IsValid(value, validationContext); } } public class StringLengthAttribute : System.ComponentModel.DataAnnotations.StringLengthAttribute { public StringLengthAttribute(int maximumLength) : base(maximumLength) { } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { validationContext.DisplayName = ModelMetadataProviders .Current .GetMetadataForProperty(null, validationContext.ObjectType, validationContext.DisplayName) .DisplayName; return base.IsValid(value, validationContext); } } 

etc....

+1
source

Hooray! The problem with the code-code reports that this error will be fixed in the Web API v5.1 Preview.

+2
source

All Articles