Search code examples
c#asp.net.netasp.net-coreaction-filter

How to use ActionFilter once to perform on all controller


I have a situation where I need one Filter to be executed before every api call but in dot net you have to write that filter above every controller. [ActionFilterName].

I have so many controllers written and writing this tag above every controller is kind of hectic. Is there any way that this filter will be called before every controller execution without writing it above every controller. Like we get in Java's Spring boot there we don't need to write our filter annotation above every controller it just gets executed before API call.

I font know if this question is similar to already asked question if yes please tell me guys I'm new here.


Solution

  • For asp.net core 2.x,try this:

    services.AddMvc(options =>
    {
        options.Filters.Add(new CustomActionFilter());  
        //or 
        //options.Filters.Add(typeof(CustomActionFilter));      
    }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    

    Reference:

    https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-2.2#filter-scopes-and-order-of-execution-1

    For asp.net core 3.x,try this:

    services.AddControllers(config =>
    {
        config.Filters.Add(new CustomActionFilter());
    });
    

    Reference:

    https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-5.0#filter-scopes-and-order-of-execution