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

时间:2013-11-04 21:50:50

标签: c# asp.net-mvc asp.net-mvc-4 asp.net-mvc-areas

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

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

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

而且,如果我在路线后注册我的区域,我的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" }
        );
    }

2 个答案:

答案 0 :(得分:24)

有两件事需要考虑

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

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

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

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

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

    enter image description here

    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" }
                );
            }
        }
    

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

答案 1 :(得分:0)

对于MVC5,我做了@Snesh所做的事情,但这没有完全起作用。如果它们具有相同的名称,它将只解析我所在区域的控制器,而不解析项目根目录中的控制器。我不得不在RegisterAreaRegisterRoutes的{​​{1}}方法中都将命名空间指定为参数。

RouteConfig.cs

RouteConfig.cs

AreaRegistration.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 }
        );
    }
相关问题