An action filter runs around an ASP.NET Core MVC action after model binding. It can change bound arguments before invocation, replace the result afterward, or stop the action from running. section 30.4.3
Use action filters when request processing depends on model-bound action data:
- Run logic in OnActionExecuting before the action method and OnActionExecuted afterward. section 30.4.3
- Inspect, insert, remove, or change entries in ActionArguments. section 30.4.3
- Assign Result to short-circuit the pipeline and return an action result without invoking the action. section 30.3 section 30.4.3
- Inspect or replace the action result and examine cancellation or exceptions through ActionExecutedContext. section 30.4.3
- Apply filters to controllers and action methods, not Razor Pages; use page filters for the Razor Pages equivalent. section 30.4.3
Changing a bound action argument
A filter can rewrite an argument after model binding and before the action runs: `public class ChangeArgAttribute : ActionFilterAttribute { public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { if (context.ActionArguments.ContainsKey("message1")) context.ActionArguments["message1"] = "New message"; await next(); } }`. Applying `[ChangeArg]` to a `Messages(string message1, string message2 = "None")` action causes the action to receive the replacement value.
Table 30.2 The filter types (view table figure)
| Name |
Description |
|---|---|
| Authorization filters |
This type of filter is used to apply the application’s authorization policy. |
| Resource filters |
This type of filter is used to intercept requests, typically to implement features such as caching. |
| Action filters |
This type of filter is used to modify the request before it is received by an action method or to modify the action result after it has been produced. This type of filter can be applied only to controllers and actions. |
| Page filters |
This type of filter is used to modify the request before it is received by a Razor Page handler method or to modify the action result after it has been produced. This type of filter can be applied only to Razor Pages. |
| Result filters |
This type of filter is used to alter the action result before it is executed or to modify the result after execution. |
| Exception filters |
This type of filter is used to handle exceptions that occur during the execution of the action method or page handler. |
Compare action filters with authorization, resource, page, result, and exception filters by purpose and endpoint scope. section 30.3
