Ste*_*ger 28 c# vb.net asp.net-mvc asp.net-mvc-3
在MVC3中,我有以下几个方面:
- 移动
- 砂箱
然后我像这样路由地图:
context.MapRoute(
"Sandbox_default",
"Sandbox/{controller}/{action}/{id}",
new { controller = "SandboxHome", action = "Index", id = UrlParameter.Optional }
Run Code Online (Sandbox Code Playgroud)
和
context.MapRoute(
"Mobile_default",
"Mobile/{controller}/{action}/{id}",
new { controller = "MobileHome", action = "Index", id = UrlParameter.Optional }
);
Run Code Online (Sandbox Code Playgroud)
问题是这给网址如下:
和
但我希望这样:
http:// localhost:58784/Mobile/Home
http:// localhost:58784/Sandbox/Home
问题是当我将SandboxHome-Controller重命名为Home,而MobileHome-Controller重命名为Home时,它将提供所需的URL,它将无法编译,说它有两个类用于HomeController.
如何在不同区域使用相同的控制器名称?
Rob*_*ett 41
是.
正如此博客文章所述: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"}
);
Run Code Online (Sandbox Code Playgroud)
只要将区域控制器保留在自己的名称空间中即可.这会奏效.
是的,但您必须更改路由:
context.MapRoute(
"Default",
"{area}/{controller}/{action}/{id}",
new { area = "Mobile", controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Run Code Online (Sandbox Code Playgroud)
您也可以保留两条路线,但不要忘记area在默认值中定义。
当然,您必须将控制器保存在它们自己的区域命名空间中:
namespace MyApp.Areas.Mobile.Controllers
{
public class HomeController : Controller
{
...
}
}
namespace MyApp.Areas.Sandbox.Controllers
{
public class HomeController : Controller
{
...
}
}
Run Code Online (Sandbox Code Playgroud)
检查MSDN 上的此链接并查看演练。并且不要忘记查看这篇关于区域注册的MSDN 文章,因为您将不得不调用RegisterAllAreas()方法。
并且由于您仍然希望保留原始的非区域控制器,您还应该阅读Phil Haack 的这篇文章如何做到这一点(信用应该转到 @Rob 在他首先指向这篇博客文章的回答中)。