我想写有条件的条件,但是条件取决于使用它的控制器。
我已经具有自定义属性MyRequiredIfNot
。我只是不知道如何通过IsValid
方法获取有关控制器的信息。
例如:
public class MyController1 : Controller
{
public ActionResult Method1(MyModel model)
{
//Name is required !!!
}
}
public class MyController2 : MyController1
{
public ActionResult SomeMethod(MyModel model)
{
//Name is NOT required !!!
}
}
public class MyModel
{
[MyRequiredIfNot(MyController2)
public string Name { get;set; }
}
缺少实现:
public class MyRequiredIfNotAttribute : ValidationAttribute
{
public MyRequiredIfNotAttribute(Controller controller) { }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (/*came_from ?*/ is this.controller) //Missing !!!!
return ValidationResult.Success;
else
return base.IsValid(value, validationContext);
}
}
答案 0 :(得分:2)
要检索Controller
,可以尝试IActionContextAccessor
。
请按照以下步骤操作:
注册IActionContextAccessor
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
//rest services
}
MyRequiredIfNotAttribute
public class MyRequiredIfNotAttribute : RequiredAttribute//ValidationAttribute
{
private Type _type;
public MyRequiredIfNotAttribute(Type type) {
_type = type;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var actionContext = validationContext.GetRequiredService<IActionContextAccessor>();
var controllerActionDescriptor = actionContext.ActionContext.ActionDescriptor as ControllerActionDescriptor;
var controllerTypeName = controllerActionDescriptor.ControllerTypeInfo.FullName;
if (_type.FullName == controllerTypeName)
{
return ValidationResult.Success;
}
else
{
return base.IsValid(value, validationContext);
}
}
}
使用情况
public class MyModel
{
[MyRequiredIfNot(typeof(MyController))]
public string Name { get; set; }
}