使用或不使用前缀的区域路由

Routing with areas using prefix or not

在我的应用程序中,我有两个区域:PortalAdmin。我想在 XXXAreaRegistration.cs 个文件中配置路由。

我想要 Portal/{controller}/{action}Admin 面板的 /admin/{controller}/{action}

我尝试了以下配置以使其成为可能:

// AdminAreaRegistration.cs
context.MapRoute("Admin",
                 "admin/{controller}/{action}",
                 new { action = "Index", controller = "Admin" });

// PortalAreaRegistration.cs
context.MapRoute("Portal",
                 "{controller}/{action}",
                 new { action = "Index", controller = "Portal" });

对于 / 我得到我的 Portal/Index.cshtml,但是对于 /admin 我得到 404...我想在第二种情况下它寻找 AdminControllerPortal 区域,这就是我得到 404 的原因。但是如何制定解决方法来创建这样的路由?

在您调用 http://www.domain.com/admin/ your routing searching as http://www.domain.com/admin/admin 时在您的代码中,因为您的默认控制器是管理员,将默认参数设置为现有控件

我猜在诸如admin之类的区域中没有控件

更新名称SPACE

修复如下代码

 context.MapRoute("Admin",
             "admin/{controller}/{action}",
             new { action = "Index", controller="Home"},
             new string[] { "MyApp.Admin.Controllers" }  // specify the new namespace);

要解决您当前存在的路由冲突问题,请在您的 Portal 区域注册中添加约束:

// PortalAreaRegistration.cs
context.MapRoute(
    "Portal",
    "{controller}/{action}",
    new { action = "Index", controller = "Portal" },
    new { controller = "^(?!.*admin).*$" }
);

这将确保门户区域将映射到除 admin/* 之外的所有内容 {controller}/{action},因为您希望管理区域提供此服务。

当然,出于明显的原因,您不能在您的 Portal 区域中安装名为 AdminController 的控制器。