Filters in ASP.NET MVC are a powerful feature that allows developers to run code before or after specific stages in the request processing pipeline. They provide a way to encapsulate cross-cutting concerns such as logging, authentication, authorization, caching, and error handling, promoting cleaner and more maintainable code.
Types of Filters
ASP.NET MVC provides several types of filters, each serving a different purpose:
- Authorization Filters: Used to determine whether a user is authorized to access a particular action or controller.
- Action Filters: Executed before and after an action method is called. They can be used for logging, modifying the action result, etc.
- Result Filters: Executed before and after the action result is executed. They can be used to modify the response sent to the client.
- Exception Filters: Used to handle exceptions that occur during the execution of an action method.
- Global Filters: Applied to all controllers and actions in the application.
1. Authorization Filters
Authorization filters are used to restrict access to actions or controllers based on user roles or authentication status. You can use the built-in [Authorize]
attribute to apply authorization.
[Authorize(Roles = "Admin")]
public class AdminController : Controller
{
public ActionResult Index()
{
return View();
}
}
In this example, only users in the "Admin" role can access the Index
action of the AdminController
.
2. Action Filters
Action filters allow you to execute code before and after an action method runs. You can create a custom action filter by inheriting from ActionFilterAttribute
.
public class LogActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Log the action execution
var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
var actionName = filterContext.ActionDescriptor.ActionName;
System.Diagnostics.Debug.WriteLine($"Executing {actionName} in {controllerName}");
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
// Log after action execution
System.Diagnostics.Debug.WriteLine("Action executed.");
}
}
You can apply this filter to a controller or action:
[LogActionFilter]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
3. Result Filters
Result filters allow you to modify the result returned by an action method before it is sent to the client. You can create a custom result filter by inheriting from ResultFilterAttribute
.
public class CustomResultFilter : ResultFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
// Modify the result before it is executed
filterContext.Result = new ContentResult
{
Content = "This is a custom response."
};
}
}
Apply the result filter to an action:
[CustomResultFilter]
public ActionResult About()
{
return View();
}
4. Exception Filters
Exception filters are used to handle exceptions that occur during the execution of an action method. You can create a custom exception filter by inheriting from IExceptionFilter
.
public class CustomExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
// Handle the exception
filterContext.ExceptionHandled = true;
filterContext.Result = new ViewResult
{
ViewName = "Error"
};
}
}
Register the exception filter globally in the FilterConfig.cs
file:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new CustomExceptionFilter());
}
5. Global Filters
Global filters are applied to all controllers and actions in the application. You can register global filters in the FilterConfig.cs
file.
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute()); // Built-in error handling filter
filters.Add(new LogActionFilter()); // Custom action filter
}
Conclusion
Filters in ASP.NET MVC provide a robust mechanism for handling cross-cutting concerns in a clean and maintainable way. By utilizing authorization, action, result, and exception filters, developers can enhance the functionality and security of their applications while keeping the code organized and reusable.