基于ASP.NET Core中的Controller的条件要求

时间:2019-02-05 08:43:25

标签: c# asp.net-core asp.net-core-mvc model-binding

我想写有条件的条件,但是条件取决于使用它的控制器。

我已经具有自定义属性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 :(得分:2)

要检索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; }
    }