How to make ActionFilter on action method take precedence over same ActionFilter on controller

前端 未结 2 1452
时光说笑
时光说笑 2020-12-17 04:06

Since asp.net mvc has changed a lot since November, does anyone have a solution to this question:

Resolve FilterAttributes On Controller And Action

Phil said

2条回答
  •  -上瘾入骨i
    2020-12-17 05:09

    I found one way to do it by "cheating" a bit with the ordering, inheritance and the AttributeUsage parameter

    First, define your ActionFilter for the controller

    [AttributeUsage(AttributeTargets.Class)]
    public class FilterController : ActionFilterAttribute
    {
        public FilterController()
        {
            this.Order = 2;
        }
    
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (!filterContext.HttpContext.Items.Contains("WeAlreadyWentThroughThis"))
            {
                    // do our thing
                filterContext.HttpContext.Items.Add("WeAlreadyWentThroughThis", "yep");
                base.OnActionExecuted(filterContext);
            }
        }
    }
    

    Then inherit the class for your action attribute

    [AttributeUsage(AttributeTargets.Method)]
    public class FilterAction : FilterController
    {
        public FilterAction()
        {
            this.Order = 1;
        }
    }
    

    It's far from perfect since you have to rely on HttpContext and two classes (though you could use namespaces to name both classes the same). But you get compiler-enforced check of the attribute scope for class or action and you won't forget an order parameter when typing the code.

提交回复
热议问题