代码之家  ›  专栏  ›  技术社区  ›  Bigeyes

将值传递给自定义属性

  •  3
  • Bigeyes  · 技术社区  · 7 年前

    我想自定义一个属性。说

    public class IdExistAttribute : ValidationAttribute
    {
    
        protected override ValidationResult IsValid(object value,
                                                      ValidationContext validationContext)
        {
            string id= value.ToString();
            if(ListOfId.Contains(id))
            {
               return new ValidationResult("Id is already existing");
            }
    
            return ValidationResult.Success;
         }
     }
    

    问题是 ListOfId

    private string _id;
    [IdExist]
    public string Id
    {
      get{return _id;}
      set{_id=value;}
    }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Community Mohan Dere    5 年前

    ValidationContext 通过提供对已注册依赖项注入容器的访问 GetService

    引用 Andrew Lock

    如您所见,在方法调用中提供了ValidationContext。context对象包含许多与当前正在验证的对象相关的属性,还有这个方便的数字:

    公共对象GetService(类型serviceType);

    验证上下文

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var service = (IExternalService) validationContext
                             .GetService(typeof(IExternalService));
        // use service
    }