繁体   English   中英

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

[英]How to put conditional Required Attribute into class property to work with 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
}

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

您可以实现自己的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.IsNullOrWhiteSpace(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
}

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

这是我的 2 美分。 它会给你一个很好的消息,比如“当前的受让人类型值销售员需要受让人标识”它也适用于枚举。

[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;
    }
}

像这样使用它

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM