Web Api ModelState验证忽略了DisplayAttribute [英] Web Api ModelState validation is ignoring the DisplayAttribute
本文介绍了Web Api ModelState验证忽略了DisplayAttribute的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出具有以下数据注释的模型:
Given a model with these data annotations:
public class Example
{
[Required]
[Display(Name = "Activity response")]
public string ActivityResponse { get; set; }
}
我希望模型状态错误消息为活动响应字段是必需的".相反,它是必填ActivityResponse字段."
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.
为每个dataannotation属性创建一个新类
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);
}
}
等...
这篇关于Web Api ModelState验证忽略了DisplayAttribute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文