c# - 我可以使用 DataAnnotations 来验证集合属性吗?

标签 c# asp.net-web-api data-annotations

我有一个 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/

相关文章:

c# - DateTimeOffset 格式并获得与 moment.js 相同的输出

c# - MVC 4 中的部分实体类未显示数据注释

c# - 如何将数据从 .Net Web 应用程序传递到我的 Java Applet

C#:如何修复此 ArgumentOutofRangeException?

asp.net-web-api - .net 4.0 上的 Microsoft ASP.NET Web API 2

azure - 在 IIS 中托管 ASP Net Core 应用程序时无限页面加载

asp.net-web-api - 如何在 ASP.NET Web API 中设置默认序列化程序?

asp.net-mvc-3 - RemoteAttribute 验证器不会触发服务器端

.net - 使用数据注释 4.0

c# - Windows Phone 7 信息