如何将条件必需属性放入类属性以使用 WEB API? [英] How to put conditional Required Attribute into class property to work with WEB API?

查看:23
本文介绍了如何将条件必需属性放入类属性以使用 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) 使用模型状态验证

I am using Model State validation via (ActionFilterAttribute)

推荐答案

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

You can implement your own ValidationAttribute. Perhaps something like this:

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
}

这只是一个示例.它可能存在投射问题,我不确定这是解决此问题的最佳方法.

This is just a sample. It may have casting issues, and I'm not sure this is the best approach to solve this problem.

这篇关于如何将条件必需属性放入类属性以使用 WEB API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆