Jeremy F
Jeremy F

Reputation: 467

How to detect if action filter is executing due to controller scope or action method scope?

I would like to immediately return from an action filter when it is executing as a result of attachment to a controller if the action filter has also been specified on the action method. The goal is to allow me to override the controller action filter at the action method level when necessary.

I could do this if I created 2 separate action filters and have the controller specific version check for the action method one prior to execution. I'd rather avoid the creation of 2 types if possible.

Upvotes: 3

Views: 2726

Answers (2)

VahidN
VahidN

Reputation: 19136

For ASP.NET Core 1.1

var currentFilter = filterContext.ActionDescriptor
                                 .FilterDescriptors
                                 .Select(filterDescriptor => filterDescriptor)
                                 .FirstOrDefault(filterDescriptor => ReferenceEquals(filterDescriptor.Filter, this));
if (currentFilter == null)
{
    return;
}


if (currentFilter.Scope == FilterScope.Action)
{
    //...
}
if (currentFilter.Scope == FilterScope.Controller)
{
    //...
}

Upvotes: 2

Ilya Chumakov
Ilya Chumakov

Reputation: 25019

You may access Filter object from action attribute and then check the scope:

[ControllerScope]
public class HomeController : Controller
{
    [ControllerScope]
    public ActionResult Index()
    {
        return View();
    }
}

public class ActionScopeAttribute : ActionFilterAttribute
{
}

public class ControllerScopeAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var filters = FilterProviders.Providers.GetFilters(filterContext.Controller.ControllerContext,
            filterContext.ActionDescriptor)
            .ToList();

        var filter = filters.First(f => f.Instance is ControllerScopeAttribute);

        if (filter.Scope == FilterScope.Action)
        {
            //your logic
        }
        if (filter.Scope == FilterScope.Controller)
        {
            //your logic
        }
    }
}

Upvotes: 0

Related Questions