Back to: ASP.NET Core Tutorials For Beginners and Professionals
Filters in ASP.NET Core MVC
In this article, I will discuss Filters in ASP.NET Core MVC Applications with Examples. Filters are one of the most important concepts in ASP.NET Core MVC Applications, and as developers, we should be aware of this concept. So, from this and in a few upcoming articles, I will discuss ASP.NET Core MVC Filters in Detail. As part of this article, we will discuss the following pointers.
- What are Filters in ASP.NET Core MVC?
- Why are Filters in ASP.NET Core MVC?
- What are the Differences Between Filters and Middlewares in ASP.NET Core?
- Types of Filters in ASP.NET Core MVC
- Advantages and Disadvantages of Filters in ASP.NET Core MVC
- Where can we configure filters in ASP.NET Core MVC?
- Default Filters Execution Order in ASP.NET Core MVC
What are Filters in ASP.NET Core MVC?
Filters are used to add cross-cutting concerns, such as Logging, Authentication, Authorization, Exception Handling, Caching, etc., to our application. In ASP.NET Core Applications, Filters allow us to execute cross-cutting logic in the following ways:
- Before an HTTP request is handled by a controller action method.
- After an HTTP request is handled by a controller action method.
- After the response is generated but before it is sent to the client.
We have already discussed in Routing that when a client makes a request, that request comes to the Routing Engine, and then the Routing Engine 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.
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?
If that is your requirement, then you need to use Filters in your ASP.NET Core application. Filters in ASP.NET Core Applications are the Attributes that allow us to inject logic or code before or after an action method is executed.
Why are Filters in ASP.NET Core MVC?
In ASP.NET Core MVC, Filters are used to Perform cross-cutting concerns. They are as follows:
- Caching
- Logging
- Error Handling
- Modifying the Result
- Authentication and Authorization, etc.
What are the Differences Between Filters and Middlewares in ASP.NET Core?
Before proceeding further, we need to understand the differences between Filters and Middleware Components in ASP.NET Core applications. The following are the Key differences between Filters and Middleware Components:
Scope of Application (Where they Applied):
- Filters: Filters are primarily applied to individual controller actions or controllers. They are used to add specific behaviors or concerns to processing a single action or a group of actions within a controller.
- Middlewares: Middlewares are applied to the entire application’s request processing pipeline. They can handle requests and responses globally, regardless of the specific controller or action being invoked.
Execution Point (When they Execute):
- Filters: Filters execute within the ASP.NET Core Framework’s pipeline and are part of the controller/action execution process. They are triggered before or after the execution of a specific action method.
- Middlewares: Middlewares execute earlier in the Request Processing Pipeline, typically before the request reaches the ASP.NET Core MVC Controller action method. They can intercept requests and responses and perform tasks at various stages of the request processing pipeline, such as Routing, Authentication, Response Formatting, etc.
Purpose and Concerns (Why they are Used):
- Filters: Filters are designed to handle concerns specific to the ASP.NET Core MVC framework, such as Logging, Authentication, Authorization, Exception Handling, Caching, Custom Logic, etc.
- Middlewares: Middlewares are more general-purpose and can handle many concerns, including Routing, Authentication, Request/Response Logging, Compression, Security, etc.
Configuration (How they Configured):
- Filters: Filters are typically configured using attributes (e.g., [Authorize], [AllowAnonymous], etc.) on controllers or action methods. You can also register global filters in the Program Class.
- Middlewares: Middlewares are configured and ordered in the Program class (e.g., UseHttpsRedirection(), UseAuthorization(), MapControllers(), etc).
Execution Order (What is the Execution Order):
- Filters: The execution order for filters is decided based on the type of filters you are applying to the controllers and action methods. So, the order of Filters is not important.
- Middlewares: The execution order for middleware components is determined by the order in which they are added to the IApplicationBuilder pipeline, i.e., to the Request Processing Pipeline. So, the order of Middleware Components is important.
So, Filters and Middleware Components serve different purposes and have different scopes within an ASP.NET Core MVC application. Filters are more tightly integrated with the ASP.NET Core MVC framework and are applied at the controller/action level. On the other hand, Middleware Components are applied globally to the entire application.
Types of Filters in ASP.NET Core MVC
In ASP.NET Core MVC, there are several types of filters available that you can use to modify the behavior in the request and response processing pipeline. The following are the commonly used Filters in ASP.NET Core MVC Applications:
Authorization Filters in ASP.NET Core:
The Authorization Filter is used to perform Authentication and Authorization checks before an action method is executed. Examples include AuthorizeAttribute for role-based or policy-based authorization and AllowAnonymousAttribute to allow unauthenticated users to access an action.
- [Authorize]: This Built-in Filter restricts access to actions or controllers for UnAuthenticated Users. You can also specify Roles, Policies, or Claims based on which it can also decide who can access specific resources.
- [AllowAnonymous]: This Built-in Filter allows unauthenticated users to access actions or controllers.
- Custom Authentication: You can also create Custom Authentication. To do so, we need to create a class implementing the IAuthorizationFilter interface and provide implementations for the OnAuthorization method, where we need to write the custom authentication logic according to our business requirements.
Action Filters in ASP.NET Core:
The Action Filters in the ASP.NET Core MVC Application are executed before and after an action method is executed. They perform tasks like Logging, Modifying the Action’s Arguments, or Altering the Action’s Result.
In ASP.NET Core, you can create a Custom Action Filter in two ways: First, by creating a class implementing the IActionFilter interface and providing implementations for [OnActionExecuting] and [OnActionExecuted] methods. Second, by creating a class inherited from the ActionFilterAttribute class and overriding the [OnActionExecuting] and [OnActionExecuted] methods.
[OnActionExecuting] and [OnActionExecuted]: These are the two methods within a Custom Action Filter to execute logic before and after an action method is called. The OnActionExecuting method executes before the action method is invoked, and the OnActionExecuted method executes after the action method is invoked.
How Do We Apply the Custom Filter to Controllers and Action Methods in ASP.NET Core?
If the custom class is created by overriding the ActionFilterAttribute class, then it is an Attribute, and we can directly apply that Custom Filter to the Action methods or Controllers. However, you cannot apply Custom Action Filters (if the custom class is created by implementing the ActionFilter interface) directly to the controllers and action methods. For this, we need to use TypeFilter and ServiceFilter as built-in attributes.
TypeFilter and ServiceFilter are built-in attributes in ASP.NET Core that apply Custom Action Filters as Attributes to controller actions or controllers. Later, as we progress, we will discuss the differences between TypeFilter and ServiceFilter Attributes and how to use them.
Result Filters in ASP.NET Core:
The Result Filters in ASP.NET Core MVC Application runs after the action method has been executed but before the result is processed and sent to the client. This means you can modify the view or the result data before it gets rendered to the output stream. They are used for tasks such as Adding Headers to the response, Modifying the Result, etc.
In ASP.NET Core, you can create a Custom Result Filter in two ways: First, by creating a class implementing the IResultFilter interface and providing implementations for [OnResultExecuting] and [OnResultExecuted] methods. Second, by creating a class inherited from the ResultFilterAttribute class and overriding the [OnResultExecuted] and [OnResultExecuted] methods.
[OnResultExecuting] and [OnResultExecuted]: These are the two methods within a Custom Result Filter to execute logic before and after the Result is generated. The OnResultExecuting method executes before the result is generated, and the OnResultExecuted method executes after the result is generated.
Exception Filters in ASP.NET Core:
The Exception Filters are executed when an unhandled exception occurs during the execution of an action method. They are used for Logging, Error Handling, and Displaying Different Error Pages Based on the Error Status Codes.
In ASP.NET Core, you can create a Custom Exception Filter in two ways: First, you can create a class implementing the IExceptionFilter interface and provide implementations for the [OnException] method. Second, by creating a class inherited from the ExceptionFilterAttribute class and overriding the [OnException] method.
Where Can We Configure Filters in ASP.NET Core MVC?
In the ASP.NET Core MVC Application, Filters can be configured in the following three places:
Configuring Filters at Controller Level:
We can apply filters at the controller level by decorating the controller with the Filter attribute, as shown in the below code. When we apply the Filter at the controller level, it will apply to all the actions of that controller.
[Authorize] // Authorization filter applied at the controller level public class HomeController : Controller { public IActionResult Index() { // Action logic } }
Configuring Filters at Globally:
We can configure filters globally in the Program class. By adding filters as services, we can ensure they are applied globally to all controllers and actions in our application. Following is an example of configuring a global filter in the Program.cs class:
builder.Services.AddControllersWithViews(options => { options.Filters.Add(new MyGlobalFilter()); });
Action Method Level:
We can also apply filters directly to individual action methods within our controller by using the Filter Attribute, as shown in the below code. This allows us to apply specific filters only to specific action methods.
public class MyController : Controller { [MyCustomFilter] // Custom filter applied to this action public IActionResult MyAction() { // Action logic } }
Default Filters Execution Order in ASP.NET Core MVC
In ASP.NET Core MVC, filters are executed in a specific order known as the “Default Execution Order“. The default execution order ensures filters are applied properly throughout the request processing pipeline. The default execution order, from the earliest to the latest in the pipeline, is as follows:
- Authorization Filters: Authorization filters are executed first. They are responsible for checking whether the current user can access the requested resource or action. If authorization fails, the request will be short-circuited, and the action method will not be executed.
- Action Filters (Before Action Execution): Action filters with “Before Action Execution” logic are executed before the action method is invoked. These filters can perform tasks like logging, input validation, or pre-processing data.
- Model Binding: Model binding occurs at this stage. It binds incoming data to action method parameters and executes model validation.
- Action Execution: The action method itself is executed.
- Action Filters (After Action Execution): Action filters with “After Action Execution” logic are executed after the action method completes its execution. These filters can perform tasks like logging, post-processing data, etc.
- Result Filters (Before Result Execution): Result filters with “Before Result Execution” logic are executed before the action result is executed. These filters can modify the result or perform additional processing.
- Action Result Execution: The action result, which can be a view or any other result type, is executed.
- Result Filters (After Result Execution): Result filters with “After Result Execution” logic are executed after the action result has been executed. These filters can perform tasks like logging or post-processing of the result.
- Exception Filters (If an Exception Occurs): Exception filters are executed if an unhandled exception occurs during the request’s processing. These filters can handle the exception, log it, and return an appropriate error response.
In the next article, I will discuss the Exception Filter in ASP.NET Core MVC Application. In this article, I try to explain Filters in ASP.NET Core MVC Applications with Examples. I hope you understand the need for and use of filters in ASP.NET Core MVC Applications.