ASP.NET Core 2.1中的脚手架标识UI,并添加全局筛选器



我有一个ASP.NET Core 2.1应用程序,在该应用程序中我使用了Identity scaffolding,如所述

现在我有了一个用于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;
});
}

此筛选器可用于所有操作方法,但不适用于标识区域中的操作方法。如何对标识区中的所有页面进行全局筛选?

在ASP.NET Core中Filters的开头一段中,您将看到以下注释:

重要

本主题不适用于Razor Pages。ASP.NET Core 2.1及更高版本支持Razor Pages的IPageFilterIAsyncPageFilter。有关更多信息,请参阅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

最新更新