如何将条件必需属性放入类属性以使用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 )使用模型状态validation

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

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