How to make an ActionFilter on an action method a priority over the same ActionFilter on the controller

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

Allow FilterAttributes On Controller and Action

Phil said that the ActionFilter on the controller is just a shorthand for applying the attribute to all controller action methods, and it’s true that if I put the same ActionFilter attribute on the controller and on the action method, it will work twice, But this does not seem to be a natural behavior. since the compiler will not even allow you to put the same attribute directly into a method several times.

+4
source share
2 answers

A filter can take precedence over another filter by setting the Order property for each filter. For instance...

[MyFilter(Order=2)] public class MyController : Controller { [MyFilter(Order=1)] public ActionResult MyAction() { //... } } 

In this example, the filter by the action method will be performed before the filter on the controller.

NTN

+7
source

I found one way to do this by “slightly changing” with the order, inheritance, and 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 we inherit the class for your action attribute

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

This is far from ideal, as you need to rely on HttpContext and two classes (although you can use namespaces to designate both classes to be the same). But you get a compiler-verified check of the attribute area for the class or action, and you will not forget the order parameter when entering the code.

+1
source

All Articles