在MVC3中,是否可以在不同的区域中使用相同的控制器名称?

在MVC3中,我有以下几个方面:

  • 移动
  • 砂箱

然后我像这样路由地图:

context.MapRoute( "Sandbox_default", "Sandbox/{controller}/{action}/{id}", new { controller = "SandboxHome", action = "Index", id = UrlParameter.Optional } 

  context.MapRoute( "Mobile_default", "Mobile/{controller}/{action}/{id}", new { controller = "MobileHome", action = "Index", id = UrlParameter.Optional } ); 

问题是这给url如下:

HTTP://本地主机:58784 /移动/ MobileHome

HTTP://本地主机:58784 /沙盒/ SandboxHome

但我希望这样:

HTTP://本地主机:58784 /手机/家
HTTP://本地主机:58784 /沙盒/主页

问题是当我将SandboxHome-Controller重命名为Home,而MobileHome-Controller重命名为Home时,它将提供所需的URL,它将无法编译,说它有两个类用于HomeController。

如何在不同区域使用相同的控制器名称?

是。

正如此博客文章所述: http : //haacked.com/archive/2010/01/12/ambiguous-controller-names.aspx

假设您调用了RegisterAllAreas和Visual Studio生成的AreaRegistration文件。 您需要做的就是在全局ASAX中使用默认路由上的命名空间来防止冲突。

 //Map routes for the main site. This specifies a namespace so that areas can have controllers with the same name routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional }, new[]{"MyProject.Web.Controllers"} ); 

只要将区域控制器保留在自己的命名空间中。 这会奏效。

是的,但你必须改变你的路线:

 context.MapRoute( "Default", "{area}/{controller}/{action}/{id}", new { area = "Mobile", controller = "Home", action = "Index", id = UrlParameter.Optional } ); 

您也可以保留两条路线,但不要忘记在默认area中定义area

重要

当然,您必须将控制器保存在自己的区域名称空间中:

 namespace MyApp.Areas.Mobile.Controllers { public class HomeController : Controller { ... } } namespace MyApp.Areas.Sandbox.Controllers { public class HomeController : Controller { ... } } 

检查MSDN上的此链接,然后查看walktrough。 并且不要忘记查看这篇关于区域注册的MSDN文章 ,因为您将不得不调用RegisterAllAreas()方法。

既然你仍然希望保留原始的非区域控制器,你还应该阅读这篇Phil Haack的文章如何做到这一点(Credit应该在@Rob的回答中首先指向这篇博文)。