剃刀页面-在所有OnGet处理程序之后从基类调用方法

时间:2019-03-06 18:51:56

标签: c# asp.net-core razor-pages

我有一个继承自PageModel的基类(称为BmsPageModel)。我需要在每个页面上调用BmsPageModel中的一个方法,以便可以根据权限正确填充菜单。

如何使从基类继承的每个页面在每个OnGet处理程序期间/之后都调用此方法,而无需在每个页面中手动键入该方法?

2 个答案:

答案 0 :(得分:1)

当我从一个问题中学到新知识时,我会喜欢它。感谢@MikeBrind的评论和以下链接(Learn Page FiltersPage Filters上的MS文档),我可以回答这个问题并更新代码。

我还有一个基类,该基类在DbContext上设置了全局查询过滤器,因此每个用户的数据都相互过滤。我必须记住要添加到每个页面的OnGet / OnPost方法中的通用方法(称为PageLoadAsync)。现在,通过覆盖执行方法,我可以添加以下内容,而不必在每个子类中添加方法。

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
    }
}

答案 1 :(得分:0)

对于 .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);
}