In ASP.NET Core Razor Pages, how do you run code around every page handler with IPageFilter, PageModel overrides or AddRazorPages conventions, and why don't action filters apply?
answer
- selected, executing, executed
- PageModel implements IPageFilter itself
- Conventions.ConfigureFilter or a folder convention
- not on individual handler methods
- IActionFilter is never invoked for pages
basics
~10 sImplement IPageFilter or IAsyncPageFilter, whose hooks run after handler selection, before the handler and after it, and register it globally, per folder through RazorPagesOptions.Conventions, or on the PageModel. Action filters never run for pages.
solid answer
~40 sRazor Pages has its own filter interface. `IPageFilter` has `OnPageHandlerSelected` (after the handler is chosen, before model binding), `OnPageHandlerExecuting` (after binding, before the handler) and `OnPageHandlerExecuted` (after the handler, before the result); `IAsyncPageFilter` has `OnPageHandlerSelectionAsync` and `OnPageHandlerExecutionAsync`. You register one in `MvcOptions.Filters` for every page, with `AddRazorPages(o => o.Conventions.ConfigureFilter(...))`, per folder with `Conventions.AddFolderApplicationModelConvention("/Appointments", m => m.Filters.Add(...))`, or as an attribute on the `PageModel` class. Filters cannot target a single handler method. For one page, override the same methods on the `PageModel`, which implements both interfaces and runs before other page filters. Authorization, resource, result and exception filters apply to pages too, but `IActionFilter` does not: pages have no action method, so those filters are skipped.
code
csharp · 21 linespublic sealed class AppointmentAuditFilter : IAsyncPageFilter
{
public Task OnPageHandlerSelectionAsync(PageHandlerSelectedContext context)
=> Task.CompletedTask;
public async Task OnPageHandlerExecutionAsync(
PageHandlerExecutingContext context, PageHandlerExecutionDelegate next)
{
var executed = await next();
if (HttpMethods.IsPost(context.HttpContext.Request.Method)
&& executed.Exception is null)
{
var audit = context.HttpContext.RequestServices.GetRequiredService<IAuditLog>();
await audit.WriteAsync(
context.ActionDescriptor.ViewEnginePath,
context.HandlerMethod?.Name ?? "(unnamed)",
context.HttpContext.User.Identity?.Name);
}
}
}go deeper
Recall that Razor Pages use page filters with OnPageHandlerExecuting and OnPageHandlerExecuted, and that a PageModel can override them.
Explain the three page-filter stages, the registration options, and why handler methods cannot carry filter attributes.
Diagnose missing cross-cutting behaviour from action filters on pages, and choose per-folder conventions over scattered PageModel overrides.
Decide which cross-cutting concerns belong in middleware, page filters or conventions so controllers and pages stay consistent.
## Where page filters sit A Razor Pages request runs through the same MVC filter pipeline as a controller action, with one stage replaced. Authorization, resource, exception and result filters work for pages as they do for controllers. The **action filter** stage does not exist for pages; in its place run **page filters**: | Hook (`IPageFilter`) | Async form (`IAsyncPageFilter`) | Runs | |---|---|---| | `OnPageHandlerSelected` | `OnPageHandlerSelectionAsync` | after the handler is chosen, **before** model binding | | `OnPageHandlerExecuting` | `OnPageHandlerExecutionAsync` (before `next()`) | after binding, before the handler | | `OnPageHandlerExecuted` | `OnPageHandlerExecutionAsync` (after `next()`) | after the handler, before the result runs | The context objects expose what each stage can change: - `PageHandlerSelectedContext.HandlerMethod` is settable, so a filter can swap the chosen handler. - `PageHandlerExecutingContext.HandlerArguments` holds the bound parameters, and setting `Result` short-circuits the handler. - `PageHandlerExecutedContext` carries the `Result`, any `Exception` and an `ExceptionHandled` flag. ## Registering a filter For a dentist's practice that audits every change to appointments: ```csharp builder.Services.AddRazorPages(options => { // every page options.Conventions.ConfigureFilter(new RequestTimingPageFilter()); // only pages under /Pages/Appointments options.Conventions.AddFolderApplicationModelConvention( "/Appointments", model => model.Filters.Add(new AppointmentAuditFilter())); }); ``` - **Globally**: `MvcOptions.Filters` (for example through `AddMvcOptions`) applies to controllers and pages, while `Conventions.ConfigureFilter` applies to pages only. - **Per folder or page**: `AddFolderApplicationModelConvention` and `AddPageApplicationModelConvention` edit the page's application model, including its `Filters`. - **As an attribute** on the `PageModel` class, when the filter is an attribute type. - **Not on a handler method**: filter attributes on `OnPostCancelAsync` are not applied. Code that should run for one handler checks `context.HandlerMethod?.Name` inside the filter, or lives in the handler. ## The PageModel as its own filter `PageModel` implements `IPageFilter` and `IAsyncPageFilter` with virtual, empty methods. Overriding them on one page model gives a per-page hook without registering anything: ```csharp public override async Task OnPageHandlerExecutionAsync( PageHandlerExecutingContext context, PageHandlerExecutionDelegate next) { Clinic = await clinics.GetCurrentAsync(); // for every handler of this page await next(); } ``` The framework wraps these overrides in a filter whose `Order` is `int.MinValue`, so they run before other page filters on the way in and after them on the way out. Two rules: the default async implementation is what calls the synchronous methods, so overriding it without calling `base` stops them running for that page; and an async override must call `await next()` or the handler never runs. ## Why action filters are skipped An `IActionFilter` is defined around an action method and its arguments. Razor Pages has no action method in that sense; the invoker selects a handler later, after binding, and only knows how to run page filters at that stage. So a global `IActionFilter` added for controllers is simply never invoked for pages. The documented answer is to implement the logic as a page filter, or as a resource or result filter if it does not need the handler. ## Choosing the right hook | Need | Hook | |---|---| | Something every page and controller needs, independent of MVC | middleware | | Logic around page handlers for all pages | page filter via `ConfigureFilter` or `MvcOptions.Filters` | | Logic for one folder of pages | page filter via `AddFolderApplicationModelConvention` | | Data or checks for one page's handlers | override on that `PageModel` | | Logic around rendering the result | result filter, which pages also run | Middleware works with `HttpContext` and, once routing has run, the matched endpoint; page filters also see the page instance, its model, the chosen handler and its bound arguments. That access is the reason to choose a filter. ## Other conventions worth knowing - `Conventions.AddPageRoute("/Appointments/Index", "bookings")` adds a second URL for a page. - `RazorPagesOptions.RootDirectory` moves the pages root away from `/Pages`. - `AddFolderRouteModelConvention` and `AddPageRouteModelConvention` rewrite routes for a folder or page. - Authorization conventions such as `AuthorizeFolder` live on the same collection but belong to the authorization topic.
- A team adds a global IActionFilter for request logging and the Razor Pages requests never show up. Why?Action filters wrap controller action methods, and the Razor Pages invoker has no such stage; it runs page filters around the selected handler instead. The global filter is therefore never invoked for pages. Implement `IPageFilter` or `IAsyncPageFilter` (or a resource or result filter if the handler is irrelevant) and register it in `MvcOptions.Filters` or through `Conventions.ConfigureFilter`.
- How would you run extra logic only for the Cancel handler without putting it in the handler?Filter attributes cannot be applied to handler methods, so register a page filter for the page or folder and check `context.HandlerMethod?.Name == "Cancel"` in `OnPageHandlerExecutionAsync`. If only one page needs it, overriding `OnPageHandlerExecutionAsync` on that `PageModel` keeps it local.
- A global IActionFilter runs around Razor Pages handlers as well
- A filter attribute on OnPostCancelAsync applies only to that handler
- OnPageHandlerSelected runs after model binding has finished
- Page filters must be registered with AddControllersWithViews to work
- An async page filter can skip calling next() and still run the handler