如何使 IActionFilter 可用于 razor 页面?

How can I make an IActionFilter available to razor pages?

我有这个过滤器:

public class ViewBagFilter : IActionFilter
{
    private readonly ApplicationDbContext db;

    public ViewBagFilter(ApplicationDbContext _dbContext)
    {
        db = _dbContext;
    }

    public void OnActionExecuting(ActionExecutingContext context)
    {
        var controller = context.Controller as Controller;
        var dataFromDb = {db-query};
        controller.ViewBag.Example = dataFromDb;
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        // do something after the action executes
    }
}

...我在 Startup.cs 中包含这样的内容:

services.AddMvc(options =>
{
    options.Filters.Add(typeof(ViewBagFilter));
});

但是当我导航到任何 Identity razor 页面时,ViewBag.Example 不存在。

我怎样才能让它也适用于 razor 页面?

这行不通:

services.AddRazorPages(options =>
{
    options.Filters.Add(typeof(ViewBagFilter));
});

Razor Pages 中的过滤器与 MVC 不同。您将需要创建一个 Razor Pages 版本:https://www.learnrazorpages.com/razor-pages/filters

请注意,动态 ViewBag 类型在 Razor Pages PageModel 类型中不可用。