Search code examples
c#asp.net-core.net-coreaction-filterasp.net-core-3.1

.Net core Action Filter is being applied to all controllers ignoring decorators


I have defined an IAsyncActionFilter (a Microsoft Action Filter) as follows:

public class CustomActionFilter : IAsyncActionFilter
{

    public CustomActionFilter()
    {
    }

    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        // do something
    }
}

I have added its declaration under the startup in the ConfigureServices:

services.AddScoped<CustomActionFilter>();

And at the end of the ConfigureServices I configure it as a Filter:

services.AddMvc((opts) =>
{
    opts.EnableEndpointRouting = false;
    opts.Filters.Add(new CustomActionFilter());
});

Finally, I use a decorator in a controller, for a specific call, to indicate I want that filter to apply in that call:

[ApiController]
[Route("a")]
public class AController : Controller
{

    public AController()
    {
    }

    [HttpGet("aa")]
    [ServiceFilter(typeof(CustomActionFilter))]
    public async Task<IActionResult> DoubleA()
    {
        // do something after the filter is called
    }
}

So far, everything is working perfectly and the CustomActionFilter is being called before and after the DoubleA controller is made.

The problem is that ALL controllers and routes are using this CustomActionFilter regardless of the decorator.

For example in this controller:

[ApiController]
[Route("b")]
public class BController : Controller
{

    public BController()
    {
    }

    [HttpGet("bb")]
    public async Task<IActionResult> DoubleB()
    {
        // do something without any kind of Filter inervention
    }
}

The CustomActionFilter is being called before and after DoubleB as well.

Any ideas what I´m doing wrong here?


Solution

  • When you add a filter to your startup it is applied globally as per the docs

    If you want it to only apply to your action, removing it from startup should and leaving the attribute on the action should work.

    Remove this line from startup should do the trick:

    opts.Filters.Add(new CustomActionFilter());