这个问题是this question的结果。
我正在开发一个ASP.NET MVC Web应用程序。在我的项目中,我正在使用数据注释对我的视图模型类进行远程验证。我知道默认远程属性不支持服务器验证。我可以在动作方法中再次验证它。但我不想这样做是违反了关注点的分离。
所以我尝试创建自定义服务器客户端远程验证属性。我在网上找到了一个代码,我用它。但是在发生服务器验证时它会给我错误。我正在使用Ninject进行依赖注入。发生错误,因为Ninject无法在验证属性中注入依赖项。请参阅下面的方案。
这是我的自定义远程验证属性:
public class RemoteClientServerAttribute : RemoteAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
// Get the controller using reflection
Type controller = Assembly.GetExecutingAssembly().GetTypes()
.FirstOrDefault(type => type.Name.ToLower() == string.Format("{0}Controller",
this.RouteData["controller"].ToString()).ToLower());
if (controller != null)
{
// Get the action method that has validation logic
MethodInfo action = controller.GetMethods()
.FirstOrDefault(method => method.Name.ToLower() ==
this.RouteData["action"].ToString().ToLower());
if (action != null)
{
// Create an instance of the controller class
object instance = Activator.CreateInstance(controller);
// Invoke the action method that has validation logic
object response = action.Invoke(instance, new object[] { value });
if (response is JsonResult)
{
object jsonData = ((JsonResult)response).Data;
if (jsonData is bool)
{
return (bool)jsonData ? ValidationResult.Success :
new ValidationResult(this.ErrorMessage);
}
}
}
}
return ValidationResult.Success;
// If you want the validation to fail, create an instance of ValidationResult
// return new ValidationResult(base.ErrorMessageString);
}
public RemoteClientServerAttribute(string routeName)
: base(routeName)
{
}
public RemoteClientServerAttribute(string action, string controller)
: base(action, controller)
{
}
public RemoteClientServerAttribute(string action, string controller,
string areaName)
: base(action, controller, areaName)
{
}
}
这是我的控制器类
public class CategoryController : Controller
{
private ICategoryRepo categoryRepo;
public CategoryController()
{
}
public CategoryController(ICategoryRepo categoryParam)
{
this.categoryRepo = categoryParam;
}
.
.
//remote validation action
public JsonResult IsNameUnique(string Name)
{
IEnumerable<Category> categories = categoryRepo.Categories.Where(x => x.Name.Trim() == Name);
Category category = categories.FirstOrDefault();
return Json(category==null, JsonRequestBehavior.AllowGet);
}
}
验证通过客户端并到达服务器端时,它开始抛出错误。
这是错误
是的,它没有抛出任何方法发现异常,因为它找不到没有参数的构造函数。
我添加了像这样的无参数构造函数
public CategoryController()
{
categoryRepo = new CategoryRepo();
}
但问题是,如果我这样做,我使用Ninject的原因根本没有任何意义。它正在依赖。但是如果我不这样做,categoryRepo将在IsNameUnique操作中抛出null异常。那么如何在我的自定义远程验证属性中使Ninject工作?
尝试替换:
object instance = Activator.CreateInstance(controller);
同
object instance = DependencyResolver.Current.GetService(controller);
我必须指出,这是有争议的ServiceLocator
模式的用法。但我几乎没有看到如何在这个属性中做不同的事情。