2016-11-09 82 views
1

我在Controller目錄中有HomeController.cs和AccountController.cs。我在Controller目錄中添加了名爲「Admin」的新文件夾,並在其中添加了DashboardController.csasp.net mvc 5管理員路由

我想/ admin/dashboard路由到DashboardController,不幸的是/ admin/Home和/ admin/Account也會路由到它們各自的控制器。我希望/ admin/Home和/ admin /帳戶將是404.我該怎麼做?

這裏是我的RouteConfig.cs

routes.MapRoute(
      name: "Admin", 
      url: "admin/{controller}/{action}/{id}", 
      defaults: new { controller = "Dashboard", action = "Index", id = UrlParameter.Optional } 
     ); 

     routes.MapRoute(
      name: "Default", 
      url: "{controller}/{action}/{id}", 
      defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
     ); 
+0

我認爲這樣做的正確方法是,使用'areas' HTTP://www.infragistics。 COM /社區/博客/ dhananjay_kumar /存檔/ 2015/11/25 /地區,在-ASP淨mvc.aspx – Hackerman

回答

1

在管理員的路線,你需要dashboard更換{controller}如下圖所示,這樣,它不會把你的網址/admin/部分後,接下來的事情作爲控制器。:

routes.MapRoute(
     name: "Admin", 
     url: "admin/dashboard/{action}/{id}", 
     defaults: new { controller = "Dashboard", action = "Index", id = UrlParameter.Optional } 
    ); 

    routes.MapRoute(
     name: "Default", 
     url: "{controller}/{action}/{id}", 
     defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
    ); 
0

MVC路由未根據文件夾結構進行映射。 在您的url(「admin/{controller}/{action}/{id}」)中,第一個/之前的子字符串代表您的控制器的名稱。在這種情況下,您指定請求將調用「AdminController」而不是「DashboardController」。 @Wellspring給出的解決方案在這裏是正確的。

0

正如@Hackerman在評論中所建議的那樣。正確的做法是通過引入一個管理區域。這將自動爲yoursite.com/admin頁面創建路線。

要添加管理區域,請右鍵單擊您的Web項目,選擇添加>區域。

然後,您希望將Dashboard控制器和視圖置於該區域的相應文件夾中。

除了添加該區域之外,還需要使其在RouteConfig.cs中的默認路由不會拉出Admin區域中的控制器。爲此,您需要編輯Route.config.cs中的Default路由。要添加在調用MapPath方法命名空間屬性,並設置UseNamespaceFallback數據令牌爲false:

Route defaultRoute = routes.MapRoute(
    name: "Default", 
    url: "{controller}/{action}/{id}", 
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }, 
    namespaces: new[] { typeof(HomeController).Namespace } 
); 
// this makes it so the route only looks for controllers under 
// the namespace specified through the namespaces parameter 
defaultRoute.DataTokens["UseNamespaceFallback"] = false;