.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
相关产品推荐
相关产品推荐

