与区域同名的控制器 – Asp.Net MVC4

我在主/顶部区域有一个Contacts控制器,我有一个名为“Contacts”的区域。

如果我在注册顶级路线之前注册我的区域,我会将POST 404s发送到Contacts控制器:

protected void Application_Start() { AreaRegistration.RegisterAllAreas(); ModelBinders.Binders.DefaultBinder = new NullStringBinder(); RouteConfig.RegisterRoutes(RouteTable.Routes); } 

而且,如果我在路线后注册我的区域,我的404到联系人控制器就会消失,但我到联系人区域的路线现在是404s。

…记录了许多重复的控制器名称问题,但我没有找到该区域与控制器名称相同的特定方案。

…可能很容易解决。 会很感激帮助。 😀

fwiw,我正在使用显式命名空间注册我的Contacts区域:

  public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }, namespaces: new[] { "MyMvcApplication.Controllers" } ); } 

有两件事需要考虑

  1. Application_Start()方法的寄存器区域中首先是AreaRegistration.RegisterAllAreas();

  2. 如果名称冲突,请使用App_Start文件夹的RouteConfig.cs文件中的名称空间以及路由中定义的所有路由(如ContactsAreaRegistration.cs

为了复制您的方案,我创建了一个示例应用程序,并且能够成功访问以下给出的两个URL:

 HTTP://本地主机:1200 /联系人/索引

 HTTP://本地主机:1200 /联系人/联系人/索引

我的应用程序的结构如下:

在此处输入图像描述

ContactsAreaRegistration.cs文件中,我们有以下代码:

 public class ContactsAreaRegistration:AreaRegistration
     {
        公共覆盖字符串AreaName
         {
            得到
             {
                返回“联系人”;
             }
         }

         public override void RegisterArea(AreaRegistrationContext context)
         {
             context.MapRoute(
                 “Contacts_default”
                 “联系人/ {控制器} / {行动} /(编号)”,
                 new {action =“Index”,id = UrlParameter.Optional},
                名称空间:new [] {“MvcApplication1.Areas.Contacts.Controllers”}
             );
         }
     }

希望它会对你有所帮助。 如果您需要,我可以发送我创建的示例应用程序代码。 谢谢。

对于MVC5,我做了@Snesh所做的但是没有完全奏效。 它只会解析我所在区域的控制器,但如果它们具有相同的名称,则不会解析项目的根目录。 我最后必须在RouteConfig.csRegisterArea方法和RegisterRoutes方法中将命名空间指定为参数。

RouteConfig.cs

  public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // This resolves to the Controllers folder at the root of the web project namespaces: new [] { typeof(Controllers.HomeController).Namespace } ); } 

AreaRegistration.cs

  public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "Handheld_default", "Handheld/{controller}/{action}/{id}", new { action = "Index", id = UrlParameter.Optional }, namespaces: new[] { typeof(Areas.Handheld.Controllers.HomeController).Namespace } ); }