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

Tro*_*ber 7 c# asp.net-mvc asp.net-mvc-areas asp.net-mvc-4

我在主/顶部区域有一个Contacts控制器,我有一个名为"Contacts"的区域.

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

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

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

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

...可能很容易解决.很感激帮助.:-D

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" }
        );
    }
Run Code Online (Sandbox Code Playgroud)

Sne*_*esh 24

有两件事需要考虑

  1. Application_Start()方法中首先注册区域AreaRegistration.RegisterAllAreas();.

  2. 在名称冲突的情况下,使用命名空间RouteConfig.cs的文件App_Start文件夹以及在路线中定义的所有路由(如ContactsAreaRegistration.cs)

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

http://localhost:1200/Contacts/Index

http://localhost:1200/Contacts/contacts/Index

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

在此输入图像描述

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

public class ContactsAreaRegistration : AreaRegistration
    {
        public override string AreaName
        {
            get
            {
                return "Contacts";
            }
        }

        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "Contacts_default",
                "Contacts/{controller}/{action}/{id}",
                new { action = "Index", id = UrlParameter.Optional },
                namespaces: new[] { "MvcApplication1.Areas.Contacts.Controllers" }
            );
        }
    }

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

  • 使用命名空间重载MapRoute方法可以解决问题. (2认同)