Razor Pages - 在所有 OnGet 处理程序之后从基础 class 调用方法
Razor Pages - Call method from base class after all OnGet handlers
我有一个继承自 PageModel 的基础 class(称为 BmsPageModel)。我需要在每个页面上调用 BmsPageModel 中的一个方法,以便可以根据权限正确填充菜单。
如何让从我的基础 class 继承的每个页面都调用此方法 during/after 每个 OnGet 处理程序,而无需在每个页面中手动输入?
我喜欢从问题中学到新东西。感谢@MikeBrind 的评论和以下链接 (Learn Page Filters and the MS doc on Page Filters) 我可以回答这个问题并更新我的代码。
我还有一个基础 class,它在 DbContext 上设置了一个全局查询过滤器,以便每个用户的数据相互过滤。我有一个通用方法(称为 PageLoadAsync),我必须记住将其添加到每个页面的 OnGet/OnPost 方法中。现在,通过覆盖执行方法,我可以添加以下内容,而不必在每个 subclass.
中添加方法
public async override Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, PageHandlerExecutionDelegate next)
{
await PageLoadAsync();
await base.OnPageHandlerExecutionAsync(context, next);
}
如果您想将其限制为仅 OnGet 方法,您可以执行以下操作:
public override void OnPageHandlerExecuting(PageHandlerSelectedContext context)
{
if(context.HandlerMethod.MethodInfo.Name == nameof(OnGet))
{
// code placed here will only execute if the OnGet() method has been selected
}
}
对于 .Net 5 下的 razor 页面(不是 MVC),这似乎工作正常
public async override Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, PageHandlerExecutionDelegate next) {
if (context.HandlerMethod.MethodInfo.Name == "OnGet") {
// code placed here will only execute if the OnGet() method has been selected
}
// Triggers the OnGet, OnPost etc on the child / inherited class
await base.OnPageHandlerExecutionAsync(context, next);
}
我有一个继承自 PageModel 的基础 class(称为 BmsPageModel)。我需要在每个页面上调用 BmsPageModel 中的一个方法,以便可以根据权限正确填充菜单。
如何让从我的基础 class 继承的每个页面都调用此方法 during/after 每个 OnGet 处理程序,而无需在每个页面中手动输入?
我喜欢从问题中学到新东西。感谢@MikeBrind 的评论和以下链接 (Learn Page Filters and the MS doc on Page Filters) 我可以回答这个问题并更新我的代码。
我还有一个基础 class,它在 DbContext 上设置了一个全局查询过滤器,以便每个用户的数据相互过滤。我有一个通用方法(称为 PageLoadAsync),我必须记住将其添加到每个页面的 OnGet/OnPost 方法中。现在,通过覆盖执行方法,我可以添加以下内容,而不必在每个 subclass.
中添加方法public async override Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, PageHandlerExecutionDelegate next)
{
await PageLoadAsync();
await base.OnPageHandlerExecutionAsync(context, next);
}
如果您想将其限制为仅 OnGet 方法,您可以执行以下操作:
public override void OnPageHandlerExecuting(PageHandlerSelectedContext context)
{
if(context.HandlerMethod.MethodInfo.Name == nameof(OnGet))
{
// code placed here will only execute if the OnGet() method has been selected
}
}
对于 .Net 5 下的 razor 页面(不是 MVC),这似乎工作正常
public async override Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, PageHandlerExecutionDelegate next) {
if (context.HandlerMethod.MethodInfo.Name == "OnGet") {
// code placed here will only execute if the OnGet() method has been selected
}
// Triggers the OnGet, OnPost etc on the child / inherited class
await base.OnPageHandlerExecutionAsync(context, next);
}