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

.NET 6中使用[Authorize]属性时如何重定向到自定义登录页面

解决方案

1. 显式配置身份验证Cookie的跳转路径

在Program.cs的服务注册段,AddIdentity方法调用之后添加以下配置,覆盖Identity默认的带/Identity前缀的登录路径:

builder.Services.ConfigureApplicationCookie(options =>
{
    // 替换为你自定义登录页的实际路由
    options.LoginPath = "/Account/Login";
    // 可按需补充其他自定义路径配置
    options.AccessDeniedPath = "/Account/AccessDenied";
    options.LogoutPath = "/Account/Logout";
});

注意:这段配置必须放在AddIdentity调用之后,否则会被Identity的默认规则覆盖。

2. 移除冗余的默认UI配置(可选,推荐)

如果你完全不需要Identity内置的Razor Pages登录、注册等页面,只使用其核心身份管理能力,可以删除AddIdentity末尾的.AddDefaultUI(),避免内置UI的路由干扰:
修改前:

builder.Services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders().AddDefaultUI();

修改后:

builder.Services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();

完成以上配置后,所有被[Authorize]属性保护的资源,未登录访问时都会自动跳转至你自定义的登录页,同时携带正确的ReturnUrl回调参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 21:36:04