ASP.NET MVC supports the following four types of filters:
Authorization Filters: Used to implement authentication and authorization logic.
Example: [Authorize]
Action Filters: Used to run code before and after an action method is called.
Example: [HandleError]
Result Filters: Used to run code before and after the action result is executed.
Example: Custom logging before a view is rendered.
Exception Filters: Used to handle exceptions thrown by action methods or action results.
Example: [HandleError] with specific exception types.
Adding Custom Filters
While the built-in filters cover many common scenarios, you can create custom filters to handle additional logic. To create a custom filter, you typically inherit from one of the filter base classes or implement an appropriate filter interface.
Example: Custom Action Filter
Let's create a custom action filter that logs the execution time of an action method.
To apply the filter globally to all controllers and actions, register it in FilterConfig.cs:
publicclassFilterConfig{publicstaticvoidRegisterGlobalFilters(GlobalFilterCollectionfilters){filters.Add(newExecutionTimeLoggerAttribute()); // Other filters}}
Make sure to call the RegisterGlobalFilters method in your Global.asax file:
ASP.NET MVC supports four built-in filter types: Authorization Filters, Action Filters, Result Filters, and Exception Filters. Developers can extend the filtering capability by creating custom filters tailored to specific needs. These custom filters can be applied at the action, controller, or global level, allowing for flexible and reusable logic throughout the application.