我有一个 ASP.NET Core 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
实现仅针对操作执行,而不针对页面处理程序执行。相反,您应该按照注释中的建议实现 IPageFilter
或 IAsyncPageFilter
:
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
)。
如果您想对操作和页面处理程序运行此操作,则您可能需要同时实现 IActionFilter
和 IPageFilter
。
关于c# - ASP.NET Core 2.1 中的 Scaffold Identity UI 并添加全局过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53741865/