如何把有条件要求的属性变成类属性与WEB API工作? [英] How to put conditional Required Attribute into class property to work with WEB API?

查看:165
本文介绍了如何把有条件要求的属性变成类属性与WEB API工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想把条件要求的属性这是与工作的 WEB API

I just want to put conditional Required Attribute which is work with 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 。也许是这样的:

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.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
}

这只是一个样本。它可能有铸造的问题,我不知道这是解决这个问题最好的办法。

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天全站免登陆