Run global filter before OnActionExecuting controller in ASP.NET Core

In an ASP.NET Core 2.0 application, I am trying to execute a global filter OnActionExecutingbefore executing a controller variant. The expected behavior is that I can prepare something in the global before and pass the value of the result to the controller. However, the current behavior is that the execution order is drawn by design.

The docs tell me about the default execution order :

Each controller that inherits the base class of the controller includes the OnActionExecuting and OnActionExecuted methods. These methods wrap the filters that run for this action: OnActionExecuting is called before any of the filters, and OnActionExecuted is called after all the filters.

This makes me interpret that Controller OnActionExecutingis running before any of the filters. Has the meaning. But the docs also indicate that the default order can be overridden by implementation IOrderedFilter.

My attempt to implement this in a filter looks like this:

public class FooActionFilter : IActionFilter, IOrderedFilter
{
    // Setting the order to 0, using IOrderedFilter, to attempt executing
    // this filter *before* the BaseController OnActionExecuting.
    public int Order => 0;

    public void OnActionExecuting(ActionExecutingContext context)
    {
        // removed logic for brevity
        var foo = "bar";

        // Pass the extracted value back to the controller
        context.RouteData.Values.Add("foo", foo);
    }
}

This filter is registered at startup as:

services.AddMvc(options => options.Filters.Add(new FooActionFilter()));

Finally, my BaseController looks like a sample below. This best explains what I'm trying to achieve:

public class BaseController : Controller
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        // The problem: this gets executed *before* the global filter.
        // I actually want the FooActionFilter to prepare this value for me.
        var foo = context.RouteData.Values.GetValueOrDefault("foo").ToString();
    }
}

Order 0 , -1, , .

: , OnActionExecuting () OnActionExecuting?

+5
2

. , 0. ControllerActionFilter int.MinValue ( ):

public class ControllerActionFilter : IAsyncActionFilter, IOrderedFilter
{
    // Controller-filter methods run farthest from the action by default.
    /// <inheritdoc />
    public int Order { get; set; } = int.MinValue;

    // ...
}

, , , - FooActionFilter.Order int.MinValue:

public class FooActionFilter : IActionFilter, IOrderedFilter
{
    public int Order => int.MinValue;

    //  ...
}

FooActionFilter ControllerActionFilter . FooActionFilter - , ControllerActionFilter - . FooActionFilter , :

"" , . , , .

+3

@CodeFuller - 2.1

0

Source: https://habr.com/ru/post/1696293/


All Articles