.NET 7中ASP.NET Core授权失败未跳转登录页反而返回404
解决.NET 7 ASP.NET Core Identity区域登录跳转404问题
1. 检查Identity区域路由配置
确认Areas/Identity/IdentityHostingStartup.cs中正确配置了区域路由,保证区域路由优先匹配:
public class IdentityHostingStartup : IHostingStartup { public void Configure(IWebHostBuilder builder) { builder.ConfigureServices((context, services) => { // 保留原有Identity服务配置 }); builder.Configure(app => { app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { // 配置区域路由规则 endpoints.MapControllerRoute( name: "areas", pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}" ); endpoints.MapDefaultControllerRoute(); endpoints.MapRazorPages(); // 必须添加,Identity基于Razor Pages }); }); } }
2. 修正Cookie认证的LoginPath配置
在Program.cs中,确保Cookie认证的LoginPath指向带区域的完整路径,并且和Identity默认认证方案关联:
// 方式1:单独配置Cookie认证 builder.Services.AddAuthentication(IdentityConstants.ApplicationScheme) .AddCookie(IdentityConstants.ApplicationScheme, options => { options.LoginPath = "/Identity/Account/Login"; options.LogoutPath = "/Identity/Account/Logout"; }); // 方式2:通过AddIdentity配置Cookie选项 builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders() .AddDefaultUI() .AddCookieAuthentication(options => { options.LoginPath = "/Identity/Account/Login"; });
3. 确认Identity页面路由正确性
如果是Scaffold生成的Identity登录页,检查Areas/Identity/Pages/Account/Login.cshtml.cs的路由属性,确保没有错误的自定义路由:
[AllowAnonymous] public class LoginModel : PageModel { // 页面默认路由即为/Identity/Account/Login,无需额外修改 // 业务逻辑代码... }
4. 调整全局路由顺序
在Program.cs的端点配置中,优先注册Identity区域的专属路由,避免被默认路由覆盖:
app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { // 先注册Identity区域路由 endpoints.MapAreaControllerRoute( name: "Identity", areaName: "Identity", pattern: "Identity/{controller=Account}/{action=Login}/{id?}" ); // 再注册默认控制器路由 endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}" ); endpoints.MapRazorPages(); });
5. 清除浏览器缓存与Cookie
浏览器可能缓存旧的认证跳转规则,清除后重新测试验证。
内容的提问来源于stack exchange,提问作者Jeffry322
相关产品推荐
相关产品推荐

