We will discuss ASP.NET Core IActionFilter in this article. Okay, let's get going.

What in ASP.NET Core are Filters?

Cross-cutting issues like logging, authentication, authorization, exception handling, caching, etc. are added via filters.

We can carry out cross-cutting logic in the following ways thanks to filters:

  • Before a controller action method handles an HTTP request.
  • Following the handling of an HTTP request by a controller action method.
  • Prior to being delivered to the client, but after the response has been prepared.

Action Filters in the Core ASP.NET
In the ASP.NET Core, action filters run both before and after an action method. They carry out operations such as logging, modifying the arguments used in the action, and changing the outcome.

IActionFilter

IActionFilter is an interface in ASP.NET Core that lets you see and control the actions that are running in your application. It offers ways to provide unique behavior both before and after an action method is called. IActionFilter is an effective tool for cross-cutting issues, but there are benefits and drawbacks to its use.

Advantages of IActionFilter

  • Cross-Cutting Concerns: It allows you to handle cross-cutting concerns like logging, validation, caching, or authentication in a clean and centralized manner instead of scattering those concerns across multiple action methods.
  • Reusable Logic: Filters can be reused across multiple controllers and actions, promoting DRY (Don't Repeat Yourself) principles in your codebase.
  • Separation of Concerns: By using action filters, you can separate concerns between the action logic and the filtering logic, leading to cleaner, more maintainable code.
  • Execution Order Control: Action filters can be ordered using the `Order` property, providing flexibility in the execution sequence of filters, which is essential for scenarios where the order of execution matters.
  • Access to Action Context: Action filters have access to the action context, allowing them to inspect and modify request data easily or affect the result that gets returned.

Disadvantages of IActionFilter

  • Complexity: Introducing filters can add complexity to your application. When multiple filters are used, understanding the execution flow can become difficult, especially with dependencies between filters.
  • Performance Overhead: Each action filter adds a slight overhead to the execution of requests, which can accumulate, particularly in high-throughput applications. It's essential to ensure that filters are efficient and necessary.
  • Tight Coupling: If not used judiciously, filters may lead to tight coupling between your API's action methods and the filters, making it harder to test and maintain individual components.
  • Limited Scope: Filters operate on action methods, meaning they cannot be applied globally to things like middleware or other request pipelines. If you need a broader application of logic, you might need a different approach.
  • Difficulty in Testing: While filters can be reusable, they can also complicate unit tests. Mocking dependencies or asserting functionality across multiple layers can become challenging.

Example
TimeActionFilter logs the execution time of action methods. The OnActionExecuting method captures the start time, while OnActionExecuted calculates the elapsed time and logs it.
// Create TimeActionFilter

  public class TimeActionFilter : IActionFilter
    {
        private Stopwatch stopwatch;

        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            stopwatch = Stopwatch.StartNew();
            Debug.WriteLine($"Stopwatch Started");
        }

        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            stopwatch.Stop();
            var elapsedMilliseconds = stopwatch.ElapsedMilliseconds;
            // log the elapsed time
            Debug.WriteLine($"Action '{filterContext.ActionDescriptor.DisplayName}' executed in {elapsedMilliseconds} ms");
        }
    }

// Register the filter in Startup.cs

public void ConfigureServices(IServiceCollection services)
  {
    services.AddControllers(options =>
     {
         options.Filters.Add(typeof(TimeActionFilter));
     });
  }

HostForLIFE ASP.NET Core 9.0 Hosting

European Best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.