[英]ASP MVC / EF6 - Using Custom Validation with Generics
I would like to know if it may be possible to use a generic class with a Custom Validator I have made. 我想知道是否可以将通用类与我制作的自定义验证器一起使用。 Here is the original code of the Custom Validator : 这是Custom Validator的原始代码:
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
}
}
I would like to have something like that instead : 我想有类似的东西:
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
}
}
The question is, how can I use such a Custom validator with one of my models ? 问题是,如何在我的一个模型中使用这样的Custom验证器? Is it even possible ? 可能吗? Here is what I would like to achieve : 这是我想要实现的目标:
public class UserModel : IManage
{
public int ID { get; set; }
[UniqueLogin<UserModel>]
public string UserName { get; set; }
public int Age { get; set; }
}
Is there a way to use generics with that kind of custom validation ? 有没有一种方法可以将泛型用于这种自定义验证?
Generic attributes are not possible in C#, see also Why does C# forbid generic attribute types? 通用属性在C#中是不可能的,另请参见为什么C#禁止通用属性类型?
Here's a workaround: 解决方法:
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);
}
}
Usage: 用法:
[UniqueLoginAttribute(typeof(UserService))]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.