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

ASP.NET Core 5 Razor Pages如何禁止未登录时重定向到/Account/Login

问题根源

你当前的配置不生效核心原因是:ConfigureApplicationCookie 是 ASP.NET Core Identity 专属的配置扩展方法,仅在项目引入 Identity 组件(调用了 AddIdentity/AddDefaultIdentity 等方法)时才会生效。你是手动注册的 Cookie 认证服务,没有使用 Identity,因此写在 ConfigureApplicationCookie 里的登录路径、跳转逻辑等配置完全没有生效,系统仍使用默认的 /Account/Login 作为未登录跳转地址。

可行解决方案

步骤1:调整Cookie认证配置

将原有的认证相关配置替换为如下代码,直接把配置写入 AddCookie 委托中,同时删除原来的整块 services.ConfigureApplicationCookie 代码:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.LoginPath = "/Index";
        options.AccessDeniedPath = "/Index";
        // 如果你不需要返回401,而是走默认重定向逻辑,可以删掉Events的自定义代码
        // 以下是按需自定义跳转逻辑的示例,不需要可以直接注释
        /*
        options.Events.OnRedirectToLogin = context =>
        {
            // 针对AJAX请求返回401,普通页面请求直接重定向到登录页
            if (context.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
            {
                context.Response.StatusCode = StatusCodes.Status401Unauthorized;
            }
            else
            {
                context.Response.Redirect(context.RedirectUri);
            }
            return Task.CompletedTask;
        };
        */
    });

步骤2:调整中间件顺序(可选但建议)

Session 中间件需要放在认证授权中间件之前,避免后续逻辑读取 Session 失败:

app.UseRouting();

// 把UseSession挪到认证授权前面
app.UseSession();

app.UseAuthentication();
app.UseAuthorization();

修改完成后重新编译启动项目,未登录访问任意受保护页面都会直接重定向到 /Index,不会再出现跳转到 /Account/Login 的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 22:33:00