如何将条件必需属性放入类属性以使用WEB API?

Shu*_*osh 20 c# custom-attributes asp.net-mvc-4 asp.net-web-api

我只想放置与WEB API一起使用的条件必需属性

public sealed class EmployeeModel
{
      [Required]
      public int CategoryId{ get; set; }
      public string Email{ get; set; } // If CategoryId == 1 then it is required
}
Run Code Online (Sandbox Code Playgroud)

我通过(ActionFilterAttribute)使用模型状态验证

vcs*_*nes 31

你可以实现自己的ValidationAttribute.也许是这样的:

public class RequireWhenCategoryAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var employee = (EmployeeModel) validationContext.ObjectInstance;
        if (employee.CategoryId == 1)
        {
            return ValidationResult.Success;
        }
        var emailStr = value as String;
        return string.IsNullOrEmpty(emailStr) ? new ValidationResult("Value is required.") : ValidationResult.Success;
    }
}

public sealed class EmployeeModel
{
    [Required]
    public int CategoryId { get; set; }
    [RequireWhenCategory]
    public string Email { get; set; } // If CategoryId == 1 then it is required
}
Run Code Online (Sandbox Code Playgroud)

这只是一个样本.它可能有铸造问题,我不确定这是解决这个问题的最佳方法.

  • @ShubhajyotiGhosh,@ ScottChamberlain:为了节省您的时间并获得一些灵活性,而不是为每个特定案例创建自定义验证属性,请查看[ExpressiveAnnotations](https://github.com/JaroslawWaliszko/ExpressiveAnnotations).通过在这种情况下使用它,您可以使用以下属性注释`Email`字段:`[RequiredIf("CategoryId == 1")]`. (4认同)
  • @ vcsjones:这是一个很好的方法,实际上我想避免控制器中的验证逻辑,因为这需要进行大量的更改(根据更改要求),我不想这样做. (2认同)
  • 实际上这个评论是错误的:If CategoryId == 1 then it is NOT required (2认同)

Kau*_*ano 7

这是我的 2 美分。它会给你一个很好的消息,比如“当前的AssigneeType值Salesman需要AssigneeId”它也适用于枚举。

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class RequiredForAnyAttribute : ValidationAttribute
{
    /// <summary>
    /// Values of the <see cref="PropertyName"/> that will trigger the validation
    /// </summary>
    public string[] Values { get; set; }

    /// <summary>
    /// Independent property name
    /// </summary>
    public string PropertyName { get; set; }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var model = validationContext.ObjectInstance;
        if (model == null || Values == null)
        {
            return ValidationResult.Success;
        }

        var currentValue = model.GetType().GetProperty(PropertyName)?.GetValue(model, null)?.ToString();
        if (Values.Contains(currentValue) && value == null)
        {
            var propertyInfo = validationContext.ObjectType.GetProperty(validationContext.MemberName);
            return new ValidationResult($"{propertyInfo.Name} is required for the current {PropertyName} value {currentValue}");
        }
        return ValidationResult.Success;
    }
}
Run Code Online (Sandbox Code Playgroud)

像这样使用它

public class SaveModel {
    [Required]
    public AssigneeType? AssigneeType { get; set; }

    [RequiredForAny(Values = new[] { nameof(AssigneeType.Salesman) }, PropertyName = nameof(AssigneeType))]
    public Guid? AssigneeId { get; set; }
}
Run Code Online (Sandbox Code Playgroud)