c# - 在 MVC3 中,是否可以在不同区域使用相同的 Controller 名称?

标签 c# asp.net-mvc vb.net asp.net-mvc-3

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

  • Mobile
  • Sandbox

然后我像这样路由 map :

    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://localhost:58784/Mobile/MobileHome

http://localhost:58784/Sandbox/SandboxHome

但我想要这样:

http://localhost:58784/Mobile/Home
http://localhost:58784/Sandbox/Home

问题是当我将 SandboxHome-Controller 重命名为 Home 并将 MobileHome-Controller 重命名为 Home 时,这将提供所需的 URL,它不会编译,说它有两个 HomeController 类。

如何在不同的区域使用相同的 Controller 名称?

最佳答案

是的。

正如这篇博文所解释的那样: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"}
 );

只要您将 Area Controller 保持在它们自己的命名空间内。这会起作用。

关于c# - 在 MVC3 中,是否可以在不同区域使用相同的 Controller 名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5065422/

相关文章:

c# - 已安装服务后如何从外部文件更改工作器服务间隔时间

c# - ASP.Net Core RouteBuilder 和依赖注入(inject)

mysql - 使用 VB.NET 2010 远程访问网站的 MySQL 数据库

c# - EF Core - 添加具有唯一索引的数据时出现重复键错误

c# - 调用相同的函数直到它连接到服务器

html - 从 URL 隐藏表单输入字段

c# - 如何按 EntityFramework 中的动态列名排序?

javascript - DataTables.js 未加载

c# - 将 VB 翻译成 C# - 类型转换

java - 指纹扫描仪