liveBook · Manning

Servlet filter

As explained in ASP.NET Core in Action, 3e

IActionFilter is an ASP.NET Core interface for synchronous MVC filters that run before and after action-method execution.

An action filter runs common code around an ASP.NET Core MVC controller action. It is useful when several actions need the same check or response customization, but that work does not belong in each action method. IActionFilter is the synchronous interface for this stage of the MVC filter pipeline. section 22.1.3 section 21.4

The filter runs after model binding, so it can inspect the arguments about to be passed to the action. Its before-action method can stop the action; its after-action method can inspect or replace the returned IActionResult. Action filters do not run for Razor Pages, which use page filters instead. section 22.1.3 section 21.2

Listing 22.5 The action filter for validating ModelState
public class ValidateModelAttribute : ActionFilterAttribute      #1
{
    public override void OnActionExecuting(                      #2
        ActionExecutingContext context)                          #2
    {
        if (!context.ModelState.IsValid)                         #3
        {
            context.Result =                                     #4
                new BadRequestObjectResult(context.ModelState);  #4
        }
    }
}

The validation example shows OnActionExecuting reading ModelState and setting context.Result to a 400 Bad Request result when validation fails. section 22.1.3

Setting context.Result before the action short-circuits action-method execution, not the entire response pipeline: result filters and result execution still run. This makes an action filter suitable for returning a validation error or 404 without putting the same check in every action. section 22.2 section 22.1.3

Choose the form and scope that fit the job:

  • Implement IActionFilter for synchronous work, or IAsyncActionFilter when a called service needs asynchronous support. Do not implement both on the same filter; only the asynchronous interface will be used. section 21.4
  • Apply a filter to one action, a controller’s actions, or globally. Scope determines which MVC requests receive the behavior. section 21.5
  • Use middleware for a concern that must reach requests beyond MVC; use a filter when it needs MVC features such as ModelState or must apply to selected actions. section 21.3

Check for a missing item before an action

An action filter reads the bound id from context.ActionArguments, asks a service whether the item exists, and sets context.Result to NotFoundResult if it does not. The action can then concentrate on fetching and returning an existing item. section 22.1.3 section 22.1

A filter is often applied through an attribute, but an attribute cannot receive an ordinary service through its constructor. For constructor injection, put the behavior in a separate IActionFilter class and apply it through TypeFilterAttribute or ServiceFilterAttribute. A filter that uses a service can also be registered globally without being an attribute. section 22.3

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains execution timing, action arguments, short-circuiting, scope, and dependency injection through worked filter examples.
Examples
Uses ModelState validation, a missing-item check, and a refactored web API controller to demonstrate action filters.
What it assumes
Builds on controller actions, model binding, validation, and IActionResult while introducing the filter interfaces and pipeline.
What you can do after
Build it from scratch as a synchronous MVC action filter that checks bound arguments or validation state and can bypass an action.
How it connects
Connects IActionFilter to model binding, ModelState, IActionResult, page filters, middleware, and dependency injection.

Also explained in

Compare how 3 books explain servlet filter →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.