22 Creating custom MVC and Razor Page filters

 

This chapter covers

  • Creating custom filters to refactor complex action methods
  • Using authorization filters to protect your action methods and Razor Pages
  • Short-circuiting the filter pipeline to bypass action and page handler execution
  • Injecting dependencies into filters

In chapter 21 I introduced the Model-View-Controller (MVC) and Razor Pages filter pipeline and showed where it fits into the life cycle of a request. You learned how to apply filters to your action method, controllers, and Razor Pages, and the effect of scope on the filter execution order.

In this chapter you’ll take that knowledge and apply it to a concrete example. You’ll learn to create custom filters that you can use in your own apps and how to use them to reduce duplicate code in your action methods.

In section 22.1 I take you through the filter types in detail, how they fit into the MVC pipeline, and what to use them for. For each one, I’ll provide example implementations that you might use in your own application and describe the built-in options available.

A key feature of filters is the ability to short-circuit a request by generating a response and halting progression through the filter pipeline. This is similar to the way short-circuiting works in middleware, but there are subtle differences for MVC filters. On top of that, the exact behavior is slightly different for each filter, and I cover that in section 22.2.

22.1 Creating custom filters for your application

22.1.1 Authorization filters: Protecting your APIs

22.1.2 Resource filters: Short-circuiting your action methods

22.1.3 Action filters: Customizing model binding and action results

22.1.4 Exception filters: Custom exception handling for your action methods

22.1.5 Result filters: Customizing action results before they execute

22.1.6 Page filters: Customizing model binding for Razor Pages

22.2 Understanding pipeline short-circuiting

22.3 Using dependency injection with filter attributes

Summary