使用验证属性验证集合中的每个字符串

时间:2019-10-30 14:32:03

标签: c# .net-core validationattribute

我的API有一个POST端点,该端点希望在正文中提供一个值列表,并且每个值应符合一组基本规则。

例如,预期的JSON应该如下所示:

{
    "someReferences" : [
        "SomeRef_001", 
        "SomeRef_002", 
        "SomeRef_001"
    ]
}

出于参数的考虑,我们将说这里的每个值都应正好为11个字符长。

为了捕获此请求,我有一个简单的类:

public class SomeReferenceData 
{
    public List<string> SomeReferences { get; set; }
}

我想使用验证属性来验证SomeReferences属性中每个值的长度是否符合规则集,即它们都为11个字符长。

是否可以使用内置的验证属性来做到这一点?


我知道我可以创建自己的验证属性来执行此操作(如下所示),但是我希望内置一些内容。

public class EachInCollectionAttribute : ValidationAttribute
{
    public int MinInclusiveLength { get; set; }
    public int MaxInclusiveLength { get; set; }

    public EachInCollectionAttribute() { }

    public EachInCollectionAttribute(int minInclusiveLength, int maxInclusiveLength)
    {
        MinInclusiveLength = minInclusiveLength;
        MaxInclusiveLength = maxInclusiveLength;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (validationContext.GetType().GetInterface(nameof(IEnumerable)) == null)
        {
            throw new InvalidOperationException(
                $"Type {value.GetType().Name} is not supported by the {nameof(EachInCollectionAttribute)} as it does not implement {nameof(IEnumerable)}");
        }
        foreach(var v in value as IEnumerable)
        {
            string vString = v.ToString();
            if (vString.Length <= MinInclusiveLength || vString.Length <= MaxInclusiveLength)
            {
                return new ValidationResult(
                    $"The value {vString} does does not conform to the length requirements of min {MinInclusiveLength}, max {MaxInclusiveLength}");
            }
        }
        return ValidationResult.Success;
    }
}

public class SomeReferenceData 
{
    [EachInCollection(minInclusiveLength: 11, maxInclusiveLength: 11)]
    public List<string> SomeReferences { get; set; }
}

编辑:另一个选择是创建一个单独的可验证对象,其中包含必要的验证属性,然后创建一个辅助对象,其中包含这些属性的集合。例如:

public class SomeReference 
{
    [Required]
    [StringLength(maximumLength: 11, MinimumLength = 11)]
    public string Value { get; set; }
}

public class SomeReferenceCollection 
{
    [Required]
    public List<SomeReference> References { get; set; }
}

但是,使用这种方法意味着预期的JSON必须进行如下更改(我希望避免):

{
    "someReferences" : [
        {
            value: "SomeRef_001"
        },
        {
            value: "SomeRef_002"
        },
        {
            value: "SomeRef_001"
        },
    ]
}

0 个答案:

没有答案
相关问题