Filters
Filters allow code to run before or after specific stages in the request processing pipeline.
Filter types
Authorization Filters
Run first
Determine whether the user is authorized for the request. If not, Short-circuit the pipeline.
Resource Filter
Runs after authorization.
OnResourceExecuting
runs code before the rest of the filter pipeline. For example, before model binding.OnResourceExecuted
runs code after the rest of the pipeline has completed.
Action/Endpoint Filters
Runs immediately before and after an action method is called.
Can change the arguments passed/result returned into/from an action.
Not supported in Razor pages.
Can be invoked on both actions and route handler-based endpoints.
Synchronous Action Filters
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.
}
}
Asynchronous Action Filteres
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.
}
}
Built-in Filter Attributes
ActionFilterAttribute
ExceptionFilterAttribute
ResultFilterAttribute
FormatFilterAttribute
ServiceFilterAttribute
public class ResponseHeaderAttribute : ActionFilterAttribute
{
private readonly string _name;
private readonly string _value;
public ResponseHeaderAttribute(string name, string value) =>
(_name, _value) = (name, value);
public override void OnResultExecuting(ResultExecutingContext context)
{
context.HttpContext.Response.Headers.Add(_name, _value);
base.OnResultExecuting(context);
}
}
[ResponseHeader("Filter-Header", "Filter Value")]
public class ResponseHeaderController : ControllerBase
{
public IActionResult Index() =>
Content("Examine the response headers using the F12 developer tools.");
// ...
Last updated
Was this helpful?