必需的属性取决于另一个属性的值(ASP.NET Core Web Api)

Required attribute dependent on another attribute's value (ASP.NET Core Web Api)

我有一个模型 class,我想在参数 "required" 上进行修改,前提是另一个参数的值是某个值。

[JsonConverter(typeof(JsonStringEnumConverter))]
[Required]
public AddressTagEnum AddressTagId { get; set; }

[RequiredIf("AddressTagId", 3)]
[MaxLength(20)]
public string AddressTagOther { get; set; }

我怎样才能做到这一点? 提前致谢。

有几种方法可以解决您的问题:

  1. 没有标准的方法可以做到这一点
  2. 有图书馆员,例如Expressive Annotations 应该有帮助
  3. 有一个内置属性 Remote 可让您执行服务器验证,例如:[Remote(action: "VerifyEmail", controller: "Users")] 请参阅 docs

我更喜欢(我知道这是基于意见的)IValidatableObject 的实现。引用文档:

public class ValidatableMovie : IValidatableObject
{
    private const int _classicYear = 1960;

    public int Id { get; set; }

    [Required]
    [StringLength(100)]
    public string Title { get; set; }

    [DataType(DataType.Date)]
    [Display(Name = "Release Date")]
    public DateTime ReleaseDate { get; set; }

    [Required]
    [StringLength(1000)]
    public string Description { get; set; }

    [Range(0, 999.99)]
    public decimal Price { get; set; }

    public Genre Genre { get; set; }

    public bool Preorder { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (Genre == Genre.Classic && ReleaseDate.Year > _classicYear)
        {
            yield return new ValidationResult(
                $"Classic movies must have a release year no later than {_classicYear}.",
                new[] { nameof(ReleaseDate) });
        }
    }
}