Filter methods for Razor Pages in ASP.NET Core


By Rick Anderson

Razor Page filters IPageFilter and IAsyncPageFilter allow Razor Pages to run code before and after a Razor Page handler is run. Razor Page filters are similar to ASP.NET Core MVC action filters, except they can’t be applied to individual page handler methods.

Razor Page filters:

  • Run code after a handler method has been selected, but before model binding occurs.
  • Run code before the handler method executes, after model binding is complete.
  • Run code after the handler method executes.
  • Can be implemented on a page or globally.
  • Cannot be applied to specific page handler methods.

Code can be run before a handler method executes using the page constructor or middleware, but only Razor Page filters have access to HttpContext. Filters have a FilterContext derived parameter, which provides access to HttpContext. For example, the Implement a filter attribute sample adds a header to the response, something that can’t be done with constructors or middleware.

View or download sample code (how to download)

Razor Page filters provide the following methods, which can be applied globally or at the page level:

  • Synchronous methods:

  • Asynchronous methods:


Implement either the synchronous or the async version of a filter interface, not both. The framework checks first to see if the filter implements the async interface, and if so, it calls that. If not, it calls the synchronous interface’s method(s). If both interfaces are implemented, only the async methods are be called. The same rule applies to overrides in pages, implement the synchronous or the async version of the override, not both.

Implement Razor Page filters globally

The following code implements IAsyncPageFilter:

using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;

namespace PageFilter.Filters

    public class SampleAsyncPageFilter : IAsyncPageFilter
        private readonly ILogger _logger;

        public SampleAsyncPageFilter(ILogger logger)
            _logger = logger;

        public async Task OnPageHandlerSelectionAsync(
                                            PageHandlerSelectedContext context)
            _logger.LogDebug("Global OnPageHandlerSelectionAsync called.");
            await Task.CompletedTask;

        public async Task OnPageHandlerExecutionAsync(
                                            PageHandlerExecutingContext context,
                                            PageHandlerExecutionDelegate next)
            _logger.LogDebug("Global OnPageHandlerExecutionAsync called.");
            await next.Invoke();

In the preceding code, ILogger is not required. It’s used in the sample to provide trace information for the application.

The following code enables the SampleAsyncPageFilter in the Startup class:

public void ConfigureServices(IServiceCollection services)

    services.AddMvc(options =>
        options.Filters.Add(new SampleAsyncPageFilter(_logger));

The following code shows the complete Startup class:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PageFilter.Filters;

namespace PageFilter

    public class Startup
        ILogger _logger;
        public Startup(ILoggerFactory loggerFactory, IConfiguration configuration)
            _logger = loggerFactory.CreateLogger<GlobalFiltersLogger>();
            Configuration = configuration;

        public IConfiguration Configuration  get; 

        public void ConfigureServices(IServiceCollection services)
            services.AddMvc(options =>
                options.Filters.Add(new SampleAsyncPageFilter(_logger));

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            if (env.IsDevelopment())



The following code calls AddFolderApplicationModelConvention to apply the SampleAsyncPageFilter to only pages in /subFolder:

public void ConfigureServices(IServiceCollection services)

       .AddRazorPagesOptions(options =>
               model => model.Filters.Add(new SampleAsyncPageFilter(_logger)));

The following code implements the synchronous IPageFilter:

using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;

namespace PageFilter.Filters

    public class SamplePageFilter : IPageFilter
        private readonly ILogger _logger;

        public SamplePageFilter(ILogger logger)
            _logger = logger;

        public void OnPageHandlerSelected(PageHandlerSelectedContext context)
            _logger.LogDebug("Global sync OnPageHandlerSelected called.");

        public void OnPageHandlerExecuting(PageHandlerExecutingContext context)
            _logger.LogDebug("Global sync PageHandlerExecutingContext called.");

        public void OnPageHandlerExecuted(PageHandlerExecutedContext context)
            _logger.LogDebug("Global sync OnPageHandlerExecuted called.");

The following code enables the SamplePageFilter:

public void ConfigureServices(IServiceCollection services)

    services.AddMvc(options =>
        options.Filters.Add(new SamplePageFilter(_logger));

Implement Razor Page filters by overriding filter methods

The following code overrides the synchronous Razor Page filters:

using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;

namespace PageFilter.Pages

    public class IndexModel : PageModel
        private readonly ILogger _logger;

        public IndexModel(ILogger<IndexModel> logger)
            _logger = logger;
        public string Message  get; set; 

        public void OnGet()
        public override void OnPageHandlerSelected(
                                    PageHandlerSelectedContext context)

        public override void OnPageHandlerExecuting(
                                    PageHandlerExecutingContext context)
            Message = "Message set in handler executing";

        public override void OnPageHandlerExecuted(
                                    PageHandlerExecutedContext context)

Implement a filter attribute

The built-in attribute-based filter OnResultExecutionAsync filter can be subclassed. The following filter adds a header to the response:

using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Filters;

namespace PageFilter.Filters

    public class AddHeaderAttribute  : ResultFilterAttribute
        private readonly string _name;
        private readonly string _value;

        public AddHeaderAttribute (string name, string value)
            _name = name;
            _value = value;

        public override void OnResultExecuting(ResultExecutingContext context)
            context.HttpContext.Response.Headers.Add(_name, new string[]  _value );

The following code applies the AddHeader attribute:

[AddHeader("Author", "Rick")]
public class ContactModel : PageModel

    private readonly ILogger _logger;

    public ContactModel(ILogger<ContactModel> logger)
        _logger = logger;
    public string Message  get; set; 

    public async Task OnGetAsync()
        Message = "Your contact page.";
        await Task.CompletedTask;

See Overriding the default order for instructions on overriding the order.

See Cancellation and short circuiting for instructions to short-circuit the filter pipeline from a filter.

Authorize filter attribute

The Authorize attribute can be applied to a PageModel:

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace PageFilter.Pages

    public class ModelWithAuthFilterModel : PageModel
        public IActionResult OnGet() => Page();