You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core 7 Razor Page根目录Index.cshtml未触发会话验证过滤器

问题分析与解决方案

问题描述

我编写了一个ValidateSessionPageFilter用于检查用户会话是否过期,代码如下:

namespace SYNT.IBP.PageFilters
{
    public class ValidateSessionPageFilter : IPageFilter
    {
        public void OnPageHandlerSelected(PageHandlerSelectedContext context)
        {
            // throw new NotImplementedException();
        }

        public void OnPageHandlerExecuting(PageHandlerExecutingContext context)
        {
            bool sessionExpired = true;

            var loginUser = context.HttpContext.Session.GetData<LoginUserInfoModel>(constSSKey_LoginUserInfo);

            if (loginUser != null)
            {
                if (loginUser.LOGIN_MODE_ID > 0 && !string.IsNullOrEmpty(loginUser.LOGIN_ID))
                {
                    sessionExpired = false;
                }
            }

            if (sessionExpired)
            {
                bool isAjax = context.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest";

                context.Result = !isAjax ? new RedirectToPageResult(constPage_PageExpired) : new UnauthorizedResult();
            }
        }

        public void OnPageHandlerExecuted(PageHandlerExecutedContext context)
        {
            //throw new NotImplementedException();
        }
    }
}

在Program.cs中,我将该过滤器应用到了/ADMIN文件夹:

builder.Services.AddRazorPages().AddRazorPagesOptions(options =>
{
    options.Conventions.AddFolderApplicationModelConvention("/ADMIN", model => model.Filters.Add(new ValidateSessionPageFilter()));
});

页面文件夹结构中,根目录下有Index.cshtml,/ADMIN子文件夹内的页面会话验证正常生效,但根目录下的Index.cshtml未触发该过滤器,请问问题出在哪里?

问题原因

你当前的过滤器仅通过AddFolderApplicationModelConvention绑定到了/ADMIN文件夹下的所有页面,根目录的页面不在这个规则覆盖范围内,所以不会触发该过滤器。

解决方案

根据需求不同,有两种处理方式:

1. 将过滤器应用到根目录页面

如果需要根目录的Index.cshtml触发该过滤器,可以选择单独给根目录页面添加过滤器,或者直接全局注册过滤器:

方式A:单独给根目录Index页面添加过滤器

修改Program.cs中的配置,添加针对根目录Index页面的规则:

builder.Services.AddRazorPages().AddRazorPagesOptions(options =>
{
    // 给ADMIN文件夹添加过滤器
    options.Conventions.AddFolderApplicationModelConvention("/ADMIN", model => model.Filters.Add(new ValidateSessionPageFilter()));
    // 给根目录的Index页面添加过滤器
    options.Conventions.AddPageApplicationModelConvention("/Index", model => model.Filters.Add(new ValidateSessionPageFilter()));
});

方式B:全局注册过滤器(所有页面都触发)

如果希望所有Razor页面都应用这个会话验证过滤器,可以直接全局添加,无需按文件夹/页面单独配置:

builder.Services.AddRazorPages(options =>
{
    options.Filters.Add(new ValidateSessionPageFilter());
});

2. 调整过滤器逻辑(按需排除页面)

如果选择全局注册后需要跳过某些页面(比如登录页),可以在过滤器中添加判断逻辑,跳过特定页面:
在OnPageHandlerExecuting方法开头添加:

// 示例:跳过根目录的Login页面
var pagePath = context.HttpContext.Request.Path;
if (pagePath == "/Login")
{
    return;
}

内容的提问来源于stack exchange,提问作者Ryan Ong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 12:20:12