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 |