Filters in ASP.NET Core Web API

Filters in ASP.NET Core Web API

In this article, I will briefly introduce you to Filters in an ASP.NET Core Web API application. Filters allow us to run code before or after specific stages in the request processing pipeline. They help handle cross-cutting concerns such as logging, exception handling, authentication, and more without modifying action methods.

Why Do We Need Filters in ASP.NET Core Web API?

Filters are necessary when we need to implement cross-cutting concerns such as logging, authorization, validation, or exception handling that are not specific to a single action but apply across multiple controllers or actions.

Rather than duplicating code, filters allow us to keep this logic centralized, cleaner, and more maintainable. Filters allow us to inject such code at various stages in the request processing pipeline, ensuring consistency and reducing redundancy.

We have already discussed that when a client makes a request, that request comes to the Routing Engine, which then navigates that Request to the Controller Action Method. So, the Controller action method will handle the incoming request and send the response back to the client who initially made the request, as shown in the image below.

Why Do We Need Filters in ASP.NET Core Web API?

But what will you do if you want to execute some code or logic before or after the action method is executed, as shown in the image below?

What Are Filters in ASP.NET Core Web API?

If that is your requirement, then you need to use Filters in your ASP.NET Core Web API application.

What Are Filters in ASP.NET Core Web API?

Filters in ASP.NET Core Web API are attributes or classes that provide a way to execute code before or after an action method processes a request. They add behaviors like error handling, authentication, authorization, logging, caching, or modifying response objects before sending them back to the client.

Filters can be applied to controllers or action methods and can modify how action methods are executed. Filters make it easier to manage shared functionality without repeating the logic in controllers or action methods. The following are the Key Benefits of using Filters in ASP.NET Core Web API:

  • Code Reusability: Avoid repeating the same code across multiple controllers or actions.
  • Separation of Concerns: Keep action methods clean by separating cross-cutting concerns.
  • Maintainability: It is easier to manage and update common functionalities in one place.
Types of Filters in ASP.NET Core Web API

There are several types of filters available in ASP.NET Core Web API, each serving a different purpose:

  • Authorization Filters: Execute before any other filter to determine whether a user is authorized to execute the action. For example, check if a user is logged in before allowing access to a specific controller or action.
  • Resource Filters: These are executed after authorization filters and can manipulate the request before it reaches the action. They are useful for implementing a caching mechanism.
  • Action Filters: These are executed before and after the action method execution. They can be used, for example, to log request data or modify the action arguments.
  • Exception Filters: Handle exceptions that occur in the application. It helps handle unhandled exceptions globally by sending a custom error response to the client.
  • Result Filters: These are executed before and after the action result is executed. They are typically used to modify the response, i.e., to format the API responses.
How Do Filters Work in ASP.NET Core Web API?

When a request arrives at the ASP.NET Core Web API application, it goes through a series of stages in the pipeline. Filters are used to plug custom logic into these stages. Each filter type plays a key role in a specific phase of this pipeline. Filters are executed in a well-defined order during the request processing pipeline. When a request is received:

  • Authorization Filters: Checks if the user is authorized.
  • Resource Filters: Manipulate the request before it reaches the action. Prepares resources needed for the request.
  • Action Filters: Run custom logic before and after executing the action method.
  • Exception Filters: Captures any unhandled exceptions and provides a proper response.
  • Result Filters: Executes custom logic before the final result is sent to the client.

Each filter type implements a specific interface or derives from a base class the framework provides, allowing us to override methods to insert our custom logic. Filters can be executed synchronously or asynchronously, allowing greater flexibility in how they affect the request and response.

Layman Example to Understand Filters:

Imagine you are hosting a birthday party. To ensure the event runs smoothly:

  • Security at the Gate (Authorization Filter): You have a security guard checking the invitation cards before letting anyone enter. This ensures that only invited guests can attend.
  • Welcoming Guests (Resource Filter): Once inside, guests are greeted and guided to their designated seats. This step organizes the flow before the actual event starts.
  • Serving Cake and Drinks (Action Filter): The waiter serves cake, snacks, and drinks to each guest according to their preferences. This step executes a specific task based on input.
  • Handling Mishaps (Exception Filter): If someone accidentally spills a drink, your cleanup crew quickly resolves the issue without disturbing the party. Similarly, Exception Filters handle unexpected errors with your application.
  • Thank You Note (Result Filter): After the party, you send a personalized thank-you note to each guest for attending. This ensures a consistent response is sent to all guests (clients).

In this analogy, each “step” represents a filter that ensures the event is managed systematically. Without these filters, unauthorized guests might enter, mishaps might go unhandled, and guests might not feel attended to.

Similarly, filters in ASP.NET Core Web API ensure that our application’s operations, such as security, validation, caching, logging, and error handling, are performed consistently, making the user experience smoother and more reliable.

Where Can We Apply Filters in ASP.NET Core Web API?

Filters can be applied at different levels, providing flexibility in how broadly they affect the application:

  • Global Level: Applying filters globally affects all controllers and actions within the application. This is ideal for cross-cutting concerns that should consistently apply across the entire API.
  • Controller Level: Applying filters at the controller level affects all actions within a specific controller. This is useful when certain behaviors are needed only for particular controllers.
  • Action Level: Applying filters at the action level affects only the specific action method. This is useful for actions that require unique behaviors differing from the rest.

Note: In our next article, I will show you how to apply the filters at the above three different levels practically with some real-time examples.

Default Filter Execution Order in ASP.NET Core Web API

Understanding the execution order of filters is crucial to ensure that they interact correctly and produce the desired outcomes. ASP.NET Core processes filters in a specific order. The default filter execution order is as follows:

  • Authorization Filters – First to execute.
  • Resource Filters – Executes after authorization.
  • Action Filters – Executes immediately before and after the action method.
  • Exception Filters – Executes if there are unhandled exceptions during action execution.
  • Result Filters – Executes before the action result is sent to the client.

Note: Filters can be synchronous or asynchronous, and the Order property can also influence their execution order when multiple filters of the same type are applied.

Real-time Use Cases of Filters in ASP.NET Core Web API

The following are some of the Real-time scenarios where we can make use of Filters in an ASP.NET Core Web API application:

  • Authorization: Ensuring the user has the right permissions before executing an action.
  • Logging: Using action filters to log the details of the incoming request and outgoing response.
  • Validation: Running validation logic on the request data before it hits the action method.
  • Caching: Implementing resource filters to cache the output of frequently accessed resources.
  • Exception Handling: Using exception filters to catch and handle exceptions across different controllers and provide meaningful responses to clients.
  • Custom Headers and Response Manipulation: Add or modify HTTP headers in responses, such as adding CORS headers or custom metadata. Using result filters to modify the response before it’s sent to the client.
Differences Between Filters and Middlewares in ASP.NET Core Web API

While filters and middleware allow us to run code before or after certain stages in the request pipeline, they operate at different levels and have different scopes. Let us understand the differences between them.

  • Purpose: Middleware components are designed to handle cross-cutting concerns at the application level. Filters, on the other hand, are focused on specific points in the MVC or API pipeline (controller/action level).
  • Scope: Middleware is executed for every request entering the ASP.NET Core application, while filters are executed for requests involving the MVC or API part of the pipeline.
  • Execution Pipeline: Middleware follows the “request-response” pipeline, which means it acts on both incoming requests and outgoing responses. Filters work at different specific stages within MVC or API, such as before or after an action method or for handling exceptions.

So, in summary, Middleware provides general-purpose request/response handling for the entire application, while filters allow us to customize behaviors specifically for MVC or API controllers and actions. Please have a look at the following diagram for a better understanding.

Differences Between Filters and Middlewares in ASP.NET Core Web API

Filters in ASP.NET Core Web API provide a powerful way to inject code at various points in the request processing pipeline, helping to manage cross-cutting concerns efficiently. By understanding the different types of filters and how they work, we can create cleaner, more maintainable applications.

In the next article, I will discuss the Authorization Filters in ASP.NET Core Web API Application. In this article, I explain the basic concepts of Filters in ASP.NET Core Web API Applications. I hope you enjoy this article.

Leave a Reply

Your email address will not be published. Required fields are marked *