Mastering Asp.Net Core: Unraveling the Concepts of Attributes - Filters
Understanding Filters (another Attribute)
What are Filters? Filters in ASP.NET Core are another application of attributes. Filters are used to add pre-action or post-action behavior to controller actions, providing a way to inject cross-cutting concerns into the request/response pipeline. They are often used to implement aspects like logging, authentication, authorization, and more.
Built-in filters handle tasks such as:
Authorization, preventing access to resources a user isn't authorized for.
Response caching, short-circuiting the request pipeline to return a cached response.
Custom filters can be created to handle cross-cutting concerns. Examples of cross-cutting concerns include error handling, caching, configuration, authorization, and logging. Filters avoid duplicating code. For example, an error handling exception filter could consolidate error handling.
How Filters Works? Filters run within the ASP.NET Core action invocation pipeline, sometimes referred to as the filter pipeline. The filter pipeline runs after ASP.NET Core selects the action to execute:
Types of Filters?
Each filter type is executed at a different stage in the filter pipeline:
Authorization filters:
Run first.
Determine whether the user is authorized for the request.
Short-circuit the pipeline if the request is not authorized.
Example:
[Authorize]
Resource filters:
Run after authorization.
OnResourceExecuting runs code before the rest of the filter pipeline. For example,
OnResourceExecuting
runs code before model binding.OnResourceExecuted runs code after the rest of the pipeline has been completed.
Example:
[ResponseCache]
Action filters:
Run immediately before and after an action method is called.
Can change the arguments passed into an action.
Can change the result returned from the action.
Are not supported in Razor Pages.
Examples:
[HttpPost]
,[HttpGet]
,[ValidateAntiForgeryToken]
Endpoint filters:
Run immediately before and after an action method is called.
Can change the arguments passed into an action.
Can change the result returned from the action.
Are not supported in Razor Pages.
Can be invoked on both actions and route handler-based endpoints.
Exception filters:
Apply global policies to unhandled exceptions that occur before the response body has been written to.
Example:
[ExceptionHandler]
Result filters:
Run immediately before and after the execution of action results.
Run only when the action method executes successfully.
Are useful for logic that must surround view or formatter execution.
Examples:
[ProducesResponseType]
,[Produces]
Implementation => Synchronous Filter Example: Synchronous filters run before and after their pipeline stage. For example, OnActionExecuting is called before the action method is called. OnActionExecuted is called after the action method returns:
public class SampleActionFilter : IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
// Do something before the action executes.
}
public void OnActionExecuted(ActionExecutedContext context)
{
// Do something after the action executes.
}
}
Implementation => Asynchronous Filter Example: Asynchronous filters are defined with only single method: OnStageExecutionAsync, that takes a FilterTypeExecutingContext and FilterTypeExecutionDelegate as The FilterTypeExecutionDelegate execute the filter’s pipeline stage. For example, ActionFilter ActionExecutionDelegate calls the action method and we can write the code before and after we call action method.
public class SampleAsyncActionFilter : IAsyncActionFilter
{
public async Task OnActionExecutionAsync(
ActionExecutingContext context, ActionExecutionDelegate next)
{
// Do something before the action executes.
await next();
// Do something after the action executes.
}
}
Filter scopes and order of execution:
A filter can be added to the pipeline at one of three scopes:
Using an attribute on a controller or Razor Page.
Using an attribute on a controller action. Filter attributes cannot be applied to Razor Pages handler methods.
Globally for all controllers, actions, and Razor Pages as shown in the following code:
var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllersWithViews(options => { options.Filters.Add<GlobalSampleActionFilter>(); });
Default order of execution: When there are multiple filters for a particular stage of the pipeline, scope determines the default order of filter execution. Global filters surround class filters, which in turn surround method filters.
Following figure shows the default order of sysnchronous filter execution.
Override the default order: We can override the default sequence of filter execution by using implementing interface IOrderedFilter. This interface has property named "Order" that use to determine the order of execution. The filter with lower order value execute before the filter with higher order value. We can setup the order property using the constructor parameter.
ExampleFilter.cs
using System;
using Microsoft.AspNetCore.Mvc.Filters;
namespace Filters
{
public class ExampleFilterAttribute : Attribute, IActionFilter, IOrderedFilter
{
public int Order { get; set; }
public void OnActionExecuting(ActionExecutingContext context)
{
//To do : before the action executes
}
public void OnActionExecuted(ActionExecutedContext context)
{
//To do : after the action executes
}
}
}
Controller.cs
using System;
using Microsoft.AspNetCore.Mvc;
using Filters;
namespace Filters.Controllers
{
[ExampleFilter(Order = 1)]
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
}
When filters are run in pipeline, filters are sorted first by order and then scope. All built-in filters are implemented by IOrderFilter and set the default filter order to 0.
Cancellation and short-circuiting:
The filter pipeline can be short-circuited by setting the Result property on the ResourceExecutingContext parameter provided to the filter method. For example, the following Resource filter prevents the rest of the pipeline from executing:
public class ShortCircuitingResourceFilterAttribute : Attribute, IResourceFilter
{
public void OnResourceExecuting(ResourceExecutingContext context)
{
context.Result = new ContentResult
{
Content = nameof(ShortCircuitingResourceFilterAttribute)
};
}
public void OnResourceExecuted(ResourceExecutedContext context) { }
}
In the following code, both the [ShortCircuitingResourceFilter]
and the [ResponseHeader]
filter target the Index
action method. The ShortCircuitingResourceFilterAttribute
filter:
Runs first, because it's a Resource Filter and
ResponseHeaderAttribute
is an Action Filter.Short-circuits the rest of the pipeline.
Therefore the ResponseHeaderAttribute
filter never runs for the Index
action. This behavior would be the same if both filters were applied at the action method level, provided the ShortCircuitingResourceFilterAttribute
ran first. The ShortCircuitingResourceFilterAttribute
runs first because of its filter type:
[ResponseHeader("Filter-Header", "Filter Value")]
public class ShortCircuitingController : Controller
{
[ShortCircuitingResourceFilter]
public IActionResult Index() =>
Content($"- {nameof(ShortCircuitingController)}.{nameof(Index)}");
}
Dependency injection:
Filters can be added by type or by instance. If an instance is added, that instance is used for every request. If a type is added, it's type-activated. A type-activated filter means:
An instance is created for each request.
Any constructor dependencies are populated by dependency injection (DI).
Filters that are implemented as attributes and added directly to controller classes or action methods cannot have constructor dependencies provided by dependency injection (DI). Constructor dependencies cannot be provided by DI because attributes must have their constructor parameters supplied where they're applied.
The following filters support constructor dependencies provided from DI:
IFilterFactory implemented on the attribute.
The preceding filters can be applied to a controller or an action.
Loggers are available from DI. However, avoid creating and using filters purely for logging purposes. The built-in framework logging typically provides what's needed for logging. Logging added to filters:
Should focus on business domain concerns or behavior specific to the filter.
Should not log actions or other framework events. The built-in filters already log actions and framework events.
ServiceFilterAttribute
Service filter implementation types are registered in Program.cs
. A ServiceFilterAttribute retrieves an instance of the filter from DI.
The following code shows the LoggingResponseHeaderFilterService
class, which uses DI:
public class LoggingResponseHeaderFilterService : IResultFilter
{
private readonly ILogger _logger;
public LoggingResponseHeaderFilterService(
ILogger<LoggingResponseHeaderFilterService> logger) =>
_logger = logger;
public void OnResultExecuting(ResultExecutingContext context)
{
_logger.LogInformation(
$"- {nameof(LoggingResponseHeaderFilterService)}.{nameof(OnResultExecuting)}");
context.HttpContext.Response.Headers.Add(
nameof(OnResultExecuting), nameof(LoggingResponseHeaderFilterService));
}
public void OnResultExecuted(ResultExecutedContext context)
{
_logger.LogInformation(
$"- {nameof(LoggingResponseHeaderFilterService)}.{nameof(OnResultExecuted)}");
}
}
In the following code, LoggingResponseHeaderFilterService
is added to the DI container:
builder.Services.AddScoped<LoggingResponseHeaderFilterService>();
In the following code, the ServiceFilter
attribute retrieves an instance of the LoggingResponseHeaderFilterService
filter from DI:
[ServiceFilter(typeof(LoggingResponseHeaderFilterService))]
public IActionResult WithServiceFilter() =>
Content($"- {nameof(FilterDependenciesController)}.{nameof(WithServiceFilter)}");
When using ServiceFilterAttribute
, setting ServiceFilterAttribute.IsReusable:
Provides a hint that the filter instance may be reused outside of the request scope it was created within. The ASP.NET Core runtime doesn't guarantee:
That a single instance of the filter will be created.
The filter will not be re-requested from the DI container at some later point.
Shouldn't be used with a filter that depends on services with a lifetime other than singleton.
ServiceFilterAttribute implements IFilterFactory. IFilterFactory
exposes the CreateInstance method for creating an IFilterMetadata instance. CreateInstance
loads the specified type from DI.
TypeFilterAttribute
TypeFilterAttribute is similar to ServiceFilterAttribute, but its type isn't resolved directly from the DI container. It instantiates the type by using Microsoft.Extensions.DependencyInjection.ObjectFactory.
Because TypeFilterAttribute
types aren't resolved directly from the DI container:
Types that are referenced using the
TypeFilterAttribute
don't need to be registered with the DI container. They do have their dependencies fulfilled by the DI container.TypeFilterAttribute
can optionally accept constructor arguments for the type.
When using TypeFilterAttribute
, setting TypeFilterAttribute.IsReusable:
Provides hint that the filter instance may be reused outside of the request scope it was created within. The ASP.NET Core runtime provides no guarantees that a single instance of the filter will be created.
Should not be used with a filter that depends on services with a lifetime other than singleton.
The following example shows how to pass arguments to a type using TypeFilterAttribute
:
[TypeFilter(typeof(LoggingResponseHeaderFilter),
Arguments = new object[] { "Filter-Header", "Filter Value" })]
public IActionResult WithTypeFilter() =>
Content($"- {nameof(FilterDependenciesController)}.{nameof(WithTypeFilter)}");
Authorization filters
Authorization filters:
Are the first filters run in the filter pipeline.
Control access to action methods.
Have a before method, but no after method.
Custom authorization filters require a custom authorization framework. Prefer configuring the authorization policies or writing a custom authorization policy over writing a custom filter. The built-in authorization filter:
Calls the authorization system.
Does not authorize requests.
Do not throw exceptions within authorization filters:
The exception will not be handled.
Exception filters will not handle the exception.
Consider issuing a challenge when an exception occurs in an authorization filter.
Resource filters
Resource filters:
Implement either the IResourceFilter or IAsyncResourceFilter interface.
Execution wraps most of the filter pipeline.
Only Authorization filters run before resource filters.
Resource filters are useful to short-circuit most of the pipeline. For example, a caching filter can avoid the rest of the pipeline on a cache hit.
Action filters
Action filters do not apply to Razor Pages. Razor Pages supports IPageFilter and IAsyncPageFilter. For more information, see Filter methods for Razor Pages.
Action filters:
Implement either the IActionFilter or IAsyncActionFilter interface.
Their execution surrounds the execution of action methods.
The following code shows a sample action filter:
public class SampleActionFilter : IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
// Do something before the action executes.
}
public void OnActionExecuted(ActionExecutedContext context)
{
// Do something after the action executes.
}
}
The ActionExecutingContext provides the following properties:
ActionArguments - enables reading the inputs to an action method.
Controller - enables manipulating the controller instance.
Result - setting
Result
short-circuits execution of the action method and subsequent action filters.
Throwing an exception in an action method:
Prevents running of subsequent filters.
Unlike setting
Result
, is treated as a failure instead of a successful result.
The ActionExecutedContext provides Controller
and Result
plus the following properties:
Canceled - True if the action execution was short-circuited by another filter.
Exception - Non-null if the action or a previously run action filter threw an exception. Setting this property to null:
Effectively handles the exception.
Result
is executed as if it was returned from the action method.
For an IAsyncActionFilter
, a call to the ActionExecutionDelegate:
Executes any subsequent action filters and the action method.
Returns
ActionExecutedContext
.
Exception filters
Exception filters:
Implement IExceptionFilter or IAsyncExceptionFilter.
Can be used to implement common error handling policies.
The following sample exception filter displays details about exceptions that occur when the app is in development:
public class SampleExceptionFilter : IExceptionFilter
{
private readonly IHostEnvironment _hostEnvironment;
public SampleExceptionFilter(IHostEnvironment hostEnvironment) =>
_hostEnvironment = hostEnvironment;
public void OnException(ExceptionContext context)
{
if (!_hostEnvironment.IsDevelopment())
{
// Don't display exception details unless running in Development.
return;
}
context.Result = new ContentResult
{
Content = context.Exception.ToString()
};
}
}
The following code tests the exception filter:
[TypeFilter(typeof(SampleExceptionFilter))]
public class ExceptionController : Controller
{
public IActionResult Index() =>
Content($"- {nameof(ExceptionController)}.{nameof(Index)}");
}
Exception filters:
Don't have before and after events.
Implement OnException or OnExceptionAsync.
Handle unhandled exceptions that occur in Razor Page or controller creation, model binding, action filters, or action methods.
Do not catch exceptions that occur in resource filters, result filters, or MVC result execution.
To handle an exception, set the ExceptionHandled property to true
or assign the Result property. This stops propagation of the exception. An exception filter can't turn an exception into a "success". Only an action filter can do that.
Exception filters:
Are good for trapping exceptions that occur within actions.
Are not as flexible as error handling middleware.
Prefer middleware for exception handling. Use exception filters only where error handling differs based on which action method is called. For example, an app might have action methods for both API endpoints and for views/HTML. The API endpoints could return error information as JSON, while the view-based actions could return an error page as HTML.
Result filters
Result filters:
Implement an interface:
IResultFilter or IAsyncResultFilter
IAlwaysRunResultFilter or IAsyncAlwaysRunResultFilter
Their execution surrounds the execution of action results.
IResultFilter and IAsyncResultFilter
The following code shows a sample result filter:
public class SampleResultFilter : IResultFilter
{
public void OnResultExecuting(ResultExecutingContext context)
{
// Do something before the result executes.
}
public void OnResultExecuted(ResultExecutedContext context)
{
// Do something after the result executes.
}
}
The kind of result being executed depends on the action. An action returning a view includes all razor processing as part of the ViewResult being executed. An API method might perform some serialization as part of the execution of the result. Learn more about action results.
Result filters are only executed when an action or action filter produces an action result. Result filters are not executed when:
An authorization filter or resource filter short-circuits the pipeline.
An exception filter handles an exception by producing an action result.
The Microsoft.AspNetCore.Mvc.Filters.IResultFilter.OnResultExecuting method can short-circuit execution of the action result and subsequent result filters by setting Microsoft.AspNetCore.Mvc.Filters.ResultExecutingContext.Cancel to true
. Write to the response object when short-circuiting to avoid generating an empty response. Throwing an exception in IResultFilter.OnResultExecuting
:
Prevents execution of the action result and subsequent filters.
Is treated as a failure instead of a successful result.
When the Microsoft.AspNetCore.Mvc.Filters.IResultFilter.OnResultExecuted method runs, the response has probably already been sent to the client. If the response has already been sent to the client, it cannot be changed.
ResultExecutedContext.Canceled
is set to true
if the action result execution was short-circuited by another filter.
ResultExecutedContext.Exception
is set to a non-null value if the action result or a subsequent result filter threw an exception. Setting Exception
to null effectively handles an exception and prevents the exception from being thrown again later in the pipeline. There is no reliable way to write data to a response when handling an exception in a result filter. If the headers have been flushed to the client when an action result throws an exception, there's no reliable mechanism to send a failure code.
For an IAsyncResultFilter, a call to await next
on the ResultExecutionDelegate executes any subsequent result filters and the action result. To short-circuit, set ResultExecutingContext.Cancel to true
and don't call the ResultExecutionDelegate
:
public class SampleAsyncResultFilter : IAsyncResultFilter
{
public async Task OnResultExecutionAsync(
ResultExecutingContext context, ResultExecutionDelegate next)
{
if (context.Result is not EmptyResult)
{
await next();
}
else
{
context.Cancel = true;
}
}
}
The framework provides an abstract ResultFilterAttribute
that can be subclassed. The ResponseHeaderAttribute class shown previously is an example of a result filter attribute.
IFilterFactory
IFilterFactory implements IFilterMetadata. Therefore, an IFilterFactory
instance can be used as an IFilterMetadata
instance anywhere in the filter pipeline. When the runtime prepares to invoke the filter, it attempts to cast it to an IFilterFactory
. If that cast succeeds, the CreateInstance method is called to create the IFilterMetadata
instance that is invoked. This provides a flexible design, since the precise filter pipeline doesn't need to be set explicitly when the app starts.
IFilterFactory.IsReusable
:
Is a hint by the factory that the filter instance created by the factory may be reused outside of the request scope it was created within.
Should not be used with a filter that depends on services with a lifetime other than singleton.
The ASP.NET Core runtime doesn't guarantee:
That a single instance of the filter will be created.
The filter will not be re-requested from the DI container at some later point.
Warning
Only configure IFilterFactory.IsReusable to return true
if the source of the filters is unambiguous, the filters are stateless, and the filters are safe to use across multiple HTTP requests. For instance, don't return filters from DI that are registered as scoped or transient if IFilterFactory.IsReusable
returns true
.
IFilterFactory
can be implemented using custom attribute implementations as another approach to creating filters:
public class ResponseHeaderFilterFactory : Attribute, IFilterFactory
{
public bool IsReusable => false;
public IFilterMetadata CreateInstance(IServiceProvider serviceProvider) =>
new InternalResponseHeaderFilter();
private class InternalResponseHeaderFilter : IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context) =>
context.HttpContext.Response.Headers.Add(
nameof(OnActionExecuting), nameof(InternalResponseHeaderFilter));
public void OnActionExecuted(ActionExecutedContext context) { }
}
The filter is applied in the following code:
[ResponseHeaderFilterFactory]
public IActionResult Index() =>
Content($"- {nameof(FilterFactoryController)}.{nameof(Index)}");
IFilterFactory implemented on an attribute
Filters that implement IFilterFactory
are useful for filters that:
Don't require passing parameters.
Have constructor dependencies that need to be filled by DI.
TypeFilterAttribute implements IFilterFactory. IFilterFactory
exposes the CreateInstance method for creating an IFilterMetadata instance. CreateInstance
loads the specified type from the services container (DI).
public class SampleActionTypeFilterAttribute : TypeFilterAttribute
{
public SampleActionTypeFilterAttribute()
: base(typeof(InternalSampleActionFilter)) { }
private class InternalSampleActionFilter : IActionFilter
{
private readonly ILogger<InternalSampleActionFilter> _logger;
public InternalSampleActionFilter(ILogger<InternalSampleActionFilter> logger) =>
_logger = logger;
public void OnActionExecuting(ActionExecutingContext context)
{
_logger.LogInformation(
$"- {nameof(InternalSampleActionFilter)}.{nameof(OnActionExecuting)}");
}
public void OnActionExecuted(ActionExecutedContext context)
{
_logger.LogInformation(
$"- {nameof(InternalSampleActionFilter)}.{nameof(OnActionExecuted)}");
}
}
}
The following code shows three approaches to applying the filter:
[SampleActionTypeFilter]
public IActionResult WithDirectAttribute() =>
Content($"- {nameof(FilterFactoryController)}.{nameof(WithDirectAttribute)}");
[TypeFilter(typeof(SampleActionTypeFilterAttribute))]
public IActionResult WithTypeFilterAttribute() =>
Content($"- {nameof(FilterFactoryController)}.{nameof(WithTypeFilterAttribute)}");
[ServiceFilter(typeof(SampleActionTypeFilterAttribute))]
public IActionResult WithServiceFilterAttribute() =>
Content($"- {nameof(FilterFactoryController)}.{nameof(WithServiceFilterAttribute)}");
In the preceding code, the first approach to applying the filter is preferred.
Use middleware in the filter pipeline
Resource filters work like middleware in that they surround the execution of everything that comes later in the pipeline. But filters differ from middleware in that they're part of the runtime, which means that they have access to context and constructs.
To use middleware as a filter, create a type with a Configure
method that specifies the middleware to inject into the filter pipeline. The following example uses middleware to set a response header:
public class FilterMiddlewarePipeline
{
public void Configure(IApplicationBuilder app)
{
app.Use(async (context, next) =>
{
context.Response.Headers.Add("Pipeline", "Middleware");
await next();
});
}
}
Use the MiddlewareFilterAttribute to run the middleware:
[MiddlewareFilter(typeof(FilterMiddlewarePipeline))]
public class FilterMiddlewareController : Controller
{
public IActionResult Index() =>
Content($"- {nameof(FilterMiddlewareController)}.{nameof(Index)}");
}
Middleware filters run at the same stage of the filter pipeline as Resource filters, before model binding and after the rest of the pipeline.
Thread safety
When passing an instance of a filter into Add
, instead of its Type
, the filter is a singleton and is not thread-safe.
Thanks for your time. I hope this post was helpful and gave you a mental model for ASP.Net Core Attributes and how to create your own Custom Attributes.