Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我可以使用DataAnnotations验证集合属性吗?_C#_Asp.net Web Api_Data Annotations - Fatal编程技术网

C# 我可以使用DataAnnotations验证集合属性吗?

C# 我可以使用DataAnnotations验证集合属性吗?,c#,asp.net-web-api,data-annotations,C#,Asp.net Web Api,Data Annotations,我有一个WebAPI2控制器的模型,它的字段接收字符串的集合(列表)。是否有一种方法可以为字符串指定DataAnnotation(例如[MaxLength]),以通过验证确保列表中的字符串长度均不超过50 public class MyModel { //... [Required] public List<string> Identifiers { get; set; } // .... }

我有一个WebAPI2控制器的模型,它的字段接收字符串的集合(列表)。是否有一种方法可以为字符串指定DataAnnotation(例如[MaxLength]),以通过验证确保列表中的字符串长度均不超过50

    public class MyModel
    {
        //...

        [Required]
        public List<string> Identifiers { get; set; }

        // ....
    }
公共类MyModel
{
//...
[必需]
公共列表标识符{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;
    }
}
公共类NoStringInListBiggerThanAttribute:ValidationAttribute
{
私有只读整数长度;
公共NoStringInListBiggerThanAttribute(整型长度)
{
这个长度=长度;
}
受保护的重写ValidationResult有效(对象值,ValidationContext ValidationContext)
{
变量字符串=作为IEnumerable的值;
if(strings==null)
返回ValidationResult.Success;
var invalid=strings.Where(s=>s.Length>Length.ToArray();
如果(无效。长度>0)
返回新的ValidationResult(“以下字符串超过值:“+string.Join”(,“,无效));
返回ValidationResult.Success;
}
}
您可以将其直接放置在您的财产上:

[Required, NoStringInListBiggerThan(50)]
public List<string> Identifiers {get; set;}
[必需,NoStringInListBiggerThan(50)]
公共列表标识符{get;set;}

我知道这个问题由来已久,但对于那些偶然发现它的人来说,这是我的自定义属性版本,灵感来自公认的答案。它利用绳子的长度来完成重物的提升

/// <summary>
///     Validation attribute to assert that the members of an IEnumerable&lt;string&gt; property, field, or parameter does not exceed a maximum length
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter)]
public class EnumerableStringLengthAttribute : StringLengthAttribute
{
    /// <summary>
    ///     Constructor that accepts the maximum length of the string.
    /// </summary>
    /// <param name="maximumLength">The maximum length, inclusive.  It may not be negative.</param>
    public EnumerableStringLengthAttribute(int maximumLength) : base(maximumLength)
    {
    }
    
    /// <summary>
    ///     Override of <see cref="StringLengthAttribute.IsValid(object)" />
    /// </summary>
    /// <remarks>
    ///     This method returns <c>true</c> if the <paramref name="value" /> is null.
    ///     It is assumed the <see cref="RequiredAttribute" /> is used if the value may not be null.
    /// </remarks>
    /// <param name="value">The value to test.</param>
    /// <returns><c>true</c> if the value is null or the length of each member of the value is between the set minimum and maximum length</returns>
    /// <exception cref="InvalidOperationException"> is thrown if the current attribute is ill-formed.</exception>
    public override bool IsValid(object? value)
    {
        return value is null || ((IEnumerable<string>)value).All(s => base.IsValid(s));
    }
}

我可能希望执行[ValidateCollection(new MaxLengthAttribute(50))],以允许应用任何其他属性,而无需每个属性都进行自定义。我希望框架中有一些东西,但这将是一个后备计划。
public override bool IsValid(object? value)
{
    return value is null || ((IEnumerable<string>)value).All(s => !string.IsNullOrEmpty(s) && base.IsValid(s));
}