这个问题的后果这一问题。
我正在开发一个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
模式的用法。但是我几乎看不到该属性如何做不同的事情。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句