ModelState验证忽略了DisplayAttribute

ModelState验证忽略了DisplayAttribute

给定具有以下数据注释的模型:

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

我希望模型状态错误消息是“ Activity 响应字段是必需的”。相反,它是“ActivityResponse字段为必填字段”。

最佳答案

遇到了同样的问题,我为此采取了解决方法。
我知道这并不完美。

为每个dataannotation属性创建一个新类

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....

关于validation - Web Api ModelState验证忽略了DisplayAttribute,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14142133/

10-11 05:01