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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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://docs.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://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-5.0#filter-scopes-and-order-of-execution


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x