ASP.NET Core 2.1 中的脚手架身份 UI 并添加全局过滤器

Scaffold Identity UI in ASP.NET Core 2.1 and add Global Filter

我有一个 ASP.NET 核心 2.1 应用程序,我在其中使用身份脚手架,如 here

中所述

现在我有一个用于 OnActionExecuting 的全局过滤器

public class SmartActionFilter : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        ...
    }
}

并且在 startup.cs 中我配置了过滤器如下

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddMvc(options =>
        {
            options.Filters.Add(new AddHeaderAttribute("Author", "HaBo")); // an instance
            options.Filters.Add(typeof(SmartActionFilter)); // by type
            // options.Filters.Add(new SampleGlobalActionFilter()); // an instance
        })
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
        .AddJsonOptions(options =>
        {
            options.SerializerSettings.ContractResolver = new DefaultContractResolver();
            options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
        });
}

此过滤器可用于所有操作方法,但不适用于身份区域中的操作方法。如何让全局过滤器对身份区域中的所有页面起作用?

Filters in ASP.NET Core 的开头段落中,您会看到以下注释:

Important

This topic does not apply to Razor Pages. ASP.NET Core 2.1 and later supports IPageFilter and IAsyncPageFilter for Razor Pages. For more information, see Filter methods for Razor Pages.

这解释了为什么您的 SmartActionFilter 实现只执行操作而不执行页面处理程序。相反,您应该按照注释中的建议实施 IPageFilterIAsyncPageFilter

public class SmartActionFilter : IPageFilter
{
    public void OnPageHandlerSelected(PageHandlerSelectedContext ctx) { }

    public void OnPageHandlerExecuting(PageHandlerExecutingContext ctx)
    {
        // Your logic here.
    }

    public void OnPageHandlerExecuted(PageHandlerExecutedContext ctx)
    {
        // Example requested in comments on answer.
        if (ctx.Result is PageResult pageResult)
        {
            pageResult.ViewData["Property"] = "Value";
        }

        // Another example requested in comments.
        // This can also be done in OnPageHandlerExecuting to short-circuit the response.
        ctx.Result = new RedirectResult("/url/to/redirect/to");
    }
}

注册 SmartActionFilter 仍然按照您问题中显示的相同方式完成(使用 MvcOptions.Filters)。

如果您想 运行 这两个操作 页面处理程序,看起来您可能需要同时实现 IActionFilterIPageFilter.