ASP.NET Core WEB API:具有条件的必需参数

时间:2018-01-26 17:37:48

标签: c# asp.net-core

我的财产必须是7,30或60。

[Required]
public int FrequenciaConsulta { get; set; }

是否有类似“[必需]”的内容来检查值?

1 个答案:

答案 0 :(得分:8)

创建自定义验证属性。

public class RequiredNumberAttribute : ValidationAttribute, IClientModelValidator
{
    private int[] allowedNumbers;

    public RequiredNumberAttribute(params int[] numbers)
    {
         allowedNumbers = numbers;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        int number = (int)value;

        if (allowedNumbers.Contains(number))
        {
            return ValidationResult.Success;
        }

        return new ValidationResult($"Error: Number must be {string.Join(",", allowedNumbers)}");
    }

用法是:

[RequiredNumber(7,30,60)]
public int FrequenciaConsulta { get; set; }