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

ASP.NET Core授权时登录链接未包含Admin区域的问题修复

修复ASP.NET Core Admin区域登录跳转路径问题

当前访问Admin区域需要登录时,跳转地址为https://localhost:44329/Account/Login?ReturnUrl=%2FAdmin,而非预期的https://localhost:44329/Admin/Account/Login?ReturnUrl=%2FAdmin,问题根源是默认身份验证配置未指定Admin区域的登录路径,以下是具体修复步骤:

1. 配置身份验证Cookie的登录路径

根据你使用的身份验证方式,在Program.cs(.NET 6+)或Startup.cs(.NET 5及更早)中修改配置:

若使用原生Cookie认证:

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        // 指定Admin区域的登录路径
        options.LoginPath = "/Admin/Account/Login";
        // 可选:配置权限不足时的跳转路径
        options.AccessDeniedPath = "/Admin/Account/AccessDenied";
    });

若使用ASP.NET Core Identity:

builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();

// 配置Identity的Cookie选项
builder.Services.ConfigureApplicationCookie(options =>
{
    options.LoginPath = "/Admin/Account/Login";
    options.ReturnUrlParameter = "ReturnUrl";
});

2. 确保Account控制器归属Admin区域

确认Account控制器位于Admin区域的目录结构中,并添加[Area("Admin")]特性:

[Area("Admin")]
public class AccountController : Controller
{
    // 你的登录代码...
}

同时检查路由配置,确保区域路由优先于默认路由(区域路由需放在默认路由之前):

app.MapControllerRoute(
    name: "areas",
    pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

3. 修正登录成功后的跳转逻辑

当前登录成功后跳转的是根目录的Home/Index,若需跳转到Admin区域首页,需指定区域参数:

if (result.Succeeded)
{
    // 跳转到Admin区域的Home/Index
    return RedirectToAction("Index", "Home", new { area = "Admin" });
}

完成以上配置后,访问Admin区域需要登录时,会自动跳转到/Admin/Account/Login?ReturnUrl=%2FAdmin,登录成功后也将回到Admin区域的指定页面。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 00:30:11