ASP.NET Core 2.1 中的 Scaffold Identity UI 并添加全局过滤器
Posted
技术标签:
【中文标题】ASP.NET Core 2.1 中的 Scaffold Identity UI 并添加全局过滤器【英文标题】:Scaffold Identity UI in ASP.NET Core 2.1 and add Global Filter 【发布时间】:2019-05-13 11:45:19 【问题描述】:我有一个 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;
);
此过滤器可用于所有操作方法,但不适用于身份区域中的操作方法。如何让全局过滤器对 Identity Area 中的所有页面起作用?
【问题讨论】:
【参考方案1】:在Filters in ASP.NET Core 的开头段落中,您将看到以下注释:
重要
本主题不适用于 Razor 页面。 ASP.NET Core 2.1 及更高版本支持 Razor 页面的 IPageFilter 和 IAsyncPageFilter。如需更多信息,请参阅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
。
【讨论】:
有什么方法可以在这里设置 ViewBag 吗?在这个过滤器中? 您无法直接访问ViewBag
,但您可以向ViewData
添加属性,这些属性将在页面的cshtml 中使用ViewBag
读取。
这有帮助。希望我也可以从这里控制重定向以上是关于ASP.NET Core 2.1 中的 Scaffold Identity UI 并添加全局过滤器的主要内容,如果未能解决你的问题,请参考以下文章