ASP MVC / EF6 - 使用泛型的自定义验证

时间:2014-09-15 12:59:00

标签: c# asp.net-mvc entity-framework generics validation

我想知道是否可以使用我所制作的自定义验证器的泛型类。 以下是自定义验证器的原始代码:

public class UniqueLoginAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value,
              ValidationContext validationContext)
    {
        ErrorMessage = string.Format("The Username {0} is already used.", value.ToString());
        //Validation process
    }
}

我希望有类似的东西:

public class UniqueLoginAttribute<T> : ValidationAttribute where T : IManage
{
    protected override ValidationResult IsValid(object value,
              ValidationContext validationContext)
    {
        ErrorMessage = string.Format("The Username {0} is already used.", value.ToString())
        //EDIT
        new T().DoSomething();
        //End of Validation process
    }
}



问题是,如何在我的某个模型中使用这样的自定义验证器?它甚至可能吗?以下是我想要实现的目标:

public class UserModel : IManage
{
    public int ID { get; set; }

    [UniqueLogin<UserModel>]
    public string UserName { get; set; }

    public int Age { get; set; }
}


有没有办法在这种自定义验证中使用泛型?

1 个答案:

答案 0 :(得分:1)

C#中无法使用通用属性,另请参阅Why does C# forbid generic attribute types?

这是一个解决方法:

public class UniqueLoginAttribute : ValidationAttribute
{
    public UniqueLoginAttribute(Type managerType)
    {
        this.ManagerType = managerType;
    }

    public Type ManagerType { get; private set; }

    protected override ValidationResult IsValid(object value,
          ValidationContext validationContext)
    {
        IManage manager = Activator.CreateInstance(this.ManagerType) as IManage;

        return manager.Validate(value);
    }
}

用法:

[UniqueLoginAttribute(typeof(UserService))]