Web Api ModelState验证忽略了DisplayAttribute

Jer*_*ook 7 validation asp.net-web-api

给定具有这些数据注释的模型:

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

我希望模型状态错误消息是"活动响应字段是必需的".相反,它是"ActivityResponse字段是必需的".

小智 1

遇到了同样的问题,我为此制定了解决方法。我知道它并不完美。

为每个数据注释属性创建一个新类

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

ETC....