30 Using filters

 

This chapter covers

  • Injecting logic into request pipelines
  • Understanding the different filter types and when each is executed
  • Creating and applying filters
  • Managing the filter lifecycle and execution order

Filters inject extra logic into request processing. Filters are like middleware that is applied to a single endpoint, which can be an action or a page handler method, and they provide an elegant way to manage a specific set of requests. In this chapter, I explain how filters work, describe the different types of filters that ASP.NET Core supports, and demonstrate the use of custom filters and the filters provided by ASP.NET Core. Table 30.1 provides a guide to the chapter.

Table 30.1 Chapter guide (view table figure)

Problem

Solution

Listing

Implementing a security policy

Use an authorization filter.

16, 17

Implementing a resource policy, such as caching

Use a resource filter.

18–20

Altering the request or response for an action method

Use an action filter.

21–24

Altering the request or response for a page handler method

Use a page filter.

25–27

Inspecting or altering the result produced by an endpoint

Use a result filter.

28–30

Inspecting or altering uncaught exceptions

Use an exception filter.

31, 32

Altering the filter lifecycle

Use a filter factory or define a service.

33–36

Applying filters throughout an application

Use a global filter.

37, 38

Changing the order in which filters are applied

Implement the IOrderedFilter interface.

39–43

30.1 Preparing for this chapter

30.1.1 Enabling HTTPS Connections

30.1.2 Dropping the database

30.1.3 Running the example application

30.2 Using filters

30.3 Understanding filters

30.4 Creating custom filters

30.4.1 Understanding authorization filters

30.4.2 Understanding resource filters

30.4.3 Understanding action filters

30.4.4 Understanding page filters

30.4.5 Understanding result filters

30.4.6 Understanding exception filters

30.4.7 Creating an exception filter

30.5 Managing the filter lifecycle