Filters in ASP.NET Core

Search for a command to run...

No comments yet. Be the first to comment.
In this series, I will write about advance concepts of ASP.NET Core. This includes following topics - DI - Middleware - Filters - Request processing pipeline - Logging, Exception Handling
Query interceptor in EF core allows developer to intercept the query before or after the execution. This provides the ability of interception, modification, or suppression of the query execution. How to use Query Interceptor into code EF core exposes...
ASP.NET Core Configuration Guide Overview ASP.NET Core uses a layered configuration system where later sources override earlier ones for the same key. Configuration Priority Order Priority Source
Legacy Delphi applications often struggle with outdated UI/UX, performance issues, and monolithic architectures that make refactoring difficult. However, a full rewrite is not always feasible due to time, cost, and the risk of disrupting critical bus...
Entity Framework Core (EF Core) is a powerful and flexible object-relational mapping (ORM) framework for .NET applications, enabling developers to work with relational databases using strongly-typed .NET objects. It simplifies data access by abstract...

In this article we are going to cover some advance scenarios where Options pattern is very useful. We have covered the basic understanding of Options pattern into Options pattern in ASP.NET Core: Introduction article. Please go through it if not fami...

In this article we will learn about Options pattern in ASP.NET Core for dealing with application configurations. The Options pattern uses the C# classes to access and manage the configurations thus providing more flexibility and type safe approach to...

In ASP.NET core world , a user request is routed to appropriate controller and then action method to be executed. In some cases, user may need to run some code before or after during execution pipeline.
Filters allows some code to run before and after specific stage in request processing pipeline. ASP.NET core has provided some built in filters , user could also create custom filters as well. Filters can also avoid duplicate code, for example exception filter can consolidate the error handling.
Built in filters are used for authorization, response caching, short circuiting the request processing pipeline.
Custom filters can be used for error handling, caching, configurations and logging purposes.
Filter pipeline runs after ASP.NET Core selects the action to be executed.

Authorization filter is executed at the beginning of the request processing pipeline. This filter is used to determine whether user is authorized for request, and if not request pipeline can be short circuited.
public class AuthorizationFilter : Attribute, IAuthorizationFilter {
public void OnAuthorization(AuthorizationFilterContext context) {
context.HttpContext.Response.WriteAsync(" OnAuthorization ==> ");
}
}
Resource filter is executed just after Authorization filter. This filter can be used to implement response caching, short circuiting the pipeline.
OnResourceExecuting runs code before the model binding. OnResourceExecuted runs after rest of the pipeline is executed.
public class ResourceFilter : Attribute, IResourceFilter {
public void OnResourceExecuted(ResourceExecutedContext context) {
context.HttpContext.Response.WriteAsync(" OnResourceExecuted ==> ");
}
public void OnResourceExecuting(ResourceExecutingContext context) {
context.HttpContext.Response.WriteAsync(" OnResourceExecuting ==> ");
}
}
Action filter is executed before and after the execution of action method inside controller. A custom action filter can be used to execute some reusable code block before or after execution of controller action. Action filter can modify the arguments passed into action method or can modify the result returned from action method.
public class ActionFilter : Attribute, IActionFilter {
public void OnActionExecuted(ActionExecutedContext context) {
context.HttpContext.Response.WriteAsync(" OnActionExecuted ==> ");
}
public void OnActionExecuting(ActionExecutingContext context) {
context.HttpContext.Response.WriteAsync(" OnActionExecuting ==> ");
}
}
Exception filter can be used to handle exception during request processing pipeline. Using this filter, exceptions can be handled globally.
public class ExceptionFilter : Attribute, IExceptionFilter {
public void OnException(ExceptionContext context) {
throw new NotImplementedException();
}
}
This filter runs immediately before and after the execution of action result. This runs after completion of the action method.
public class ResultFilter : Attribute, IResultFilter {
public void OnResultExecuted(ResultExecutedContext context) {
context.HttpContext.Response.WriteAsync(" OnResultExecuted ==> ");
}
public void OnResultExecuting(ResultExecutingContext context) {
context.HttpContext.Response.WriteAsync(" OnResultExecuting ==> ");
}
}
A filter can be added to the pipeline at three levels
using an attribute, Filter can be added to pipeline
[AuthorizationFilter]
[ResourceFilter]
[ActionFilter]
[ResultFilter]
public class HomeController : Controller {
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger) {
_logger = logger;
}
public IActionResult Index() {
HttpContext.Response.WriteAsync(" Inside Action ==>");
return View();
}
}
[ActionFilter]
public IActionResult Index() {
HttpContext.Response.WriteAsync(" Inside Action ==>");
return View();
}
public void ConfigureServices(IServiceCollection services) {
services.AddControllersWithViews(option => {
option.Filters.Add<ResourceFilter>();
});
}