我有一个 WebAPI2 Controller 模型,它有一个接受字符串集合(列表)的字段。有没有一种方法可以为字符串指定 DataAnnotations(例如 [MaxLength]),以确保通过验证,列表中的所有字符串的长度都不大于 50?
public class MyModel
{
//...
[Required]
public List<string> Identifiers { get; set; }
// ....
}
我宁愿不创建一个新类来简单地包装字符串。
最佳答案
您可以编写自己的验证属性,例如如下:
public class NoStringInListBiggerThanAttribute : ValidationAttribute
{
private readonly int length;
public NoStringInListBiggerThanAttribute(int length)
{
this.length = length;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var strings = value as IEnumerable<string>;
if(strings == null)
return ValidationResult.Success;
var invalid = strings.Where(s => s.Length > length).ToArray();
if(invalid.Length > 0)
return new ValidationResult("The following strings exceed the value: " + string.Join(", ", invalid));
return ValidationResult.Success;
}
}
您可以将它直接放在您的属性(property)上:
[Required, NoStringInListBiggerThan(50)]
public List<string> Identifiers {get; set;}
关于c# - 我可以使用 DataAnnotations 来验证集合属性吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33090123/