Web Api ModelState validation is ignoring the DisplayAttribute
Given a model with these data annotations:
public class Example
{
[Required]
[Display(Name = "Activity response")]
public string ActivityResponse { get; set; }
}
I would expect the model state error message to be "The Activity response field is required." Instead it is "The ActivityResponse field is required."
Had the same problem and I made a workaround for it. I know it is not perfect.
For every 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....
Hooray! The codeplex issue reports that this bug will be fixed in Web API v5.1 Preview.
链接地址: http://www.djcxy.com/p/11650.html