Условно требуется на основе контроллера в ASP.NET Core - PullRequest
0 голосов
/ 05 февраля 2019

Я хотел бы написать условное обязательное, но условие зависит от контроллера, где оно используется.

У меня уже есть пользовательский атрибут 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);
    }
}

1 Ответ

0 голосов
/ 05 февраля 2019

Для получения Controller вы можете попробовать IActionContextAccessor.

Выполните следующие действия:

  1. Регистрация IActionContextAccessor

    public void ConfigureServices(IServiceCollection services)
    {
    
        services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
    
        //rest services
    }
    
  2. 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);
            }            
        }
    }
    
  3. Использование

    public class MyModel
    {
        [MyRequiredIfNot(typeof(MyController))]
        public string Name { get; set; }
    }
    
...