2013-03-25 125 views
13

区域的文件夹的样子:Mvc区域路由?

Areas 
    Admin 
     Controllers 
      UserController 
      BranchController 
      AdminHomeController 

项目目录,如下所示:

Controller 
    UserController 
     GetAllUsers 

地区航线登记

public override void RegisterArea(AreaRegistrationContext context) 
{ 
    context.MapRoute(
     "Admin_default", 
     "Admin/{controller}/{action}/{id}", 
     new { action = "Index", id = UrlParameter.Optional }, 
     new { controller = "Branch|AdminHome|User" } 
    ); 
} 

项目路线注册

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 string[] { "MyApp.Areas.Admin.Controllers" }); 
} 

当我像这样路由:http://mydomain.com/User/GetAllUsers我得到资源未找到错误(404)。将UserController添加到区域后出现此错误。

我该如何解决这个错误?

谢谢...

回答

26

你弄乱了你的控制器命名空间。

你的主要路线定义应该是:

routes.MapRoute(
    name: "Default", 
    url: "{controller}/{action}/{id}", 
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }, 
    namespaces: new string[] { "MyApp.Controllers" } 
); 

而且你的管理区登记的路线应该是:

public override void RegisterArea(AreaRegistrationContext context) 
{ 
    context.MapRoute(
     "Admin_default", 
     "Admin/{controller}/{action}/{id}", 
     new { action = "Index", id = UrlParameter.Optional }, 
     new { controller = "Branch|AdminHome|User" }, 
     new[] { "MyApp.Areas.Admin.Controllers" } 
    ); 
} 

注意正确的命名空间应该如何使用。

+0

我一直困惑的地区对应的命名空间。在这个例子中,名称空间MyApp.Areas.Admin.Controllers与文件夹层次结构匹配,但名称空间定义是任意的?这意味着程序员可以将任何命名空间分配给他们想要的控制器类 - 我想。或者是否有一些asp.net mvc约定需要他的命名空间来匹配文件夹层次结构? – Howiecamp 2014-08-25 05:36:53

+1

@Howiecamp Visual Studio的默认行为是将命名空间与文件夹层次结构进行匹配,这就是所有.net项目(不仅仅是MVC项目)中通常会看到的内容。 – 2014-11-26 03:42:10