在 MVC 中,如何设置 2 条路线(一条带有硬编码段,另一条带有空段)以指向同一目的地?

In MVC, how do I setup 2 routes (one with a hardcoded segment, and the other with an empty segment) to point to the same destination?

我正在尝试在我的 MVC 应用程序中设置路由,其中​​一条路由可能包含段 "Portal" 而另一条路由根本没有 "Portal" 段。本质上,我需要这些 URL 将用户发送到同一页面,但我也希望 /Home/Index 成为默认值:

/Portal/Home/Index
/Home/Index

我有以下代码:

routes.MapRoute(
    "PortalDefault", // Route name
    "Portal/{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional, portal = String.Empty } // Parameter defaults
);

这允许用户转到 /Portal/Home/Index 和 /Home/Index 但问题是该网站现在默认为 /Portal/Home/Index.

我需要网站默认为/Home/Index但仍然允许/Portal/Home/Index

一种解决方案是为主页添加一个路由以覆盖 PortalDefault

routes.MapRoute(
    "Home", // Route name
    "", // URL with parameters
    new { controller = "Home", action = "Index", portal = String.Empty } // Parameter defaults
);

routes.MapRoute(
    "PortalDefault", // Route name
    "Portal/{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional, portal = String.Empty } // Parameter defaults
);

NOTE: It seems odd that your PortalDefault route doesn't define a route value for portal, but your Default route does.