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

.NET 8中结合Areas配置UseEndpoints路由的问题

解决方案

1. 配置根URL指向Landing页面

路由匹配遵循从上到下优先匹配原则,需将根路径的配置放在最前面,提供两种实现方式供选择:

方式一:显式重定向(有地址栏跳转痕迹)

在UseEndpoints中添加根路径映射,放在所有路由配置最上方:

app.UseEndpoints(endpoints =>
{
    // 根URL重定向到Landing的静态页面
    endpoints.MapGet("/", context =>
    {
        context.Response.Redirect("/Landing/Home/index.html");
        return Task.CompletedTask;
    });

    // 配置Landing Area路由(若使用MVC控制器视图而非静态文件则保留)
    endpoints.MapAreaControllerRoute(
        name: "Landing",
        areaName: "Landing",
        pattern: "Landing/{controller=Home}/{action=Index}/{id?}");

    // Identity Area路由保持原有配置
    endpoints.MapAreaControllerRoute(
        name: "Identity",
        areaName: "Identity",
        pattern: "Identity/{controller=Home}/{action=Index}");

    // 主应用默认路由,调整默认指向Revenue/Dashboard
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Revenue}/{action=Dashboard}/{id?}");

    endpoints.MapRazorPages();
});

方式二:默认静态文件配置(无跳转痕迹)

若希望根URL直接返回Landing页面,可修改静态文件默认配置,放在UseStaticFiles之前:

// 配置默认首页为Landing的index.html
app.UseDefaultFiles(new DefaultFilesOptions
{
    FileProvider = new PhysicalFileProvider(
        Path.Combine(builder.Environment.WebRootPath, "Landing", "Home")),
    DefaultFileNames = new List<string> { "index.html" }
});

// 启用静态文件服务
app.UseStaticFiles();

// 后续路由配置同方式一

2. 确保Landing静态文件可匿名访问

将Landing打包后的所有文件(index.html、JS、CSS等)放入项目的wwwroot/Landing/Home目录,静态文件中间件默认允许匿名访问,无需额外授权配置。

3. 登录按钮跳转配置

在Landing的index.html中,直接使用绝对路径配置登录按钮跳转:

<a href="/Revenue/Dashboard" class="login-btn">登录</a>

4. 授权拦截跳转配置

在program.cs中配置身份验证Cookie的登录跳转路径,指向Identity区域的登录页面:

// 若使用AddDefaultIdentity配置身份验证
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();

// 配置授权拦截后的跳转路径
builder.Services.ConfigureApplicationCookie(options =>
{
    options.LoginPath = "/Identity/Account/Login"; // 对应Identity Area的Account控制器Login动作
    options.AccessDeniedPath = "/Identity/Account/AccessDenied";
});

关键注意事项

  • 路由顺序不可颠倒:根路径相关配置必须放在最前面,否则会被后续的Area路由或默认路由优先匹配
  • 若Landing使用MVC视图而非静态HTML,需确保Landing/Home/Index动作添加[AllowAnonymous]特性,允许匿名访问
  • Identity的登录路径需与实际路由一致,默认Identity的登录地址为/Identity/Account/Login

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 23:30:18