如何定义到多个区域的端点路由

Per*_*edt 10 c# asp.net-mvc asp.net-core-routing asp.net-core-3.0

我正在尝试定义一个MapAreaControllerRoute()到多个区域的路由。但是,在 ASP.NET Core 3.0 中,有areaName:一个需要设置的参数,因此将每个路由限制在一个区域内。我不明白如何使用一条适用于多个区域的路线。

我已经阅读了有关 Stack Overflow 的许多问题,但似乎这是 ASP.NET Core 3.0 中的一个新要求。在 ASP.NET Core <= 2.2 中,您可以在MapRoute()不定义 set的情况下创建 a areaName

就像现在一样,在 my 中Startup.cs,我将端点定义为:

app.UseEndpoints(endpoints =>
{
  endpoints.MapAreaControllerRoute(
    name: "Area1",
    areaName: "Area1",
    pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
  );

  endpoints.MapAreaControllerRoute(
    name: "Area2",
    areaName: "Area2",
    pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
  );

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

});
Run Code Online (Sandbox Code Playgroud)

当然,必须有一种方法来定义一条路线来覆盖所有区域?

Per*_*edt 13

好的,所以在阅读了额外的一堆链接之后,结果证明是区域控制器缺少属性的情况!通过使用以下标签标记控制器:

[Area("Area1")]
[Route("Area1/[controller]/[action]")]
public class Area1Controller : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}
Run Code Online (Sandbox Code Playgroud)

并将路线更改为:

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

            endpoints.MapAreaControllerRoute(
                name: "areas",
                areaName: "areas",
                pattern: "{area}/{controller=Home}/{action=Index}/{id?}"
                );
    }
Run Code Online (Sandbox Code Playgroud)

一切似乎都按预期工作。

  • 难道不应该先走更复杂的路线吗?我注意到您在原来的帖子中这样做了,但解决方案发生了变化。端点路由的文档仍然不完整且未发布,但所有以前的文档都建议使用以前的方法。所以我很好奇你为什么把它放在对面。 (3认同)
  • 在我看来,这是有效的,因为仅在 Controller 类上有 Route 属性,与对 MapAreaControllerRoute() 的调用无关。您是否在 Startup.cs 中没有该块的情况下测试了它?编辑:如果您想创建一条不特定于某个区域的路线,为什么不直接使用 MapControllerRoute() 呢? (2认同)

pse*_*der 5

您可以使用以下方法为区域编写通用模式MapControllerRoute()

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "areas",
        pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
    );
    endpoints.MapDefaultControllerRoute();
});
Run Code Online (Sandbox Code Playgroud)

那么区域控制器只需要Area属性:

[Area("AreaName")]
public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}
Run Code Online (Sandbox Code Playgroud)