Asp.net-Mvc-3

ASP.NET MVC 預設路由可通過區域路由訪問

  • July 25, 2012

到目前為止(為簡潔起見),我在 global.asax 中註冊了一條路線,如下所示:

routes.Add(new LowercaseRoute("{action}/{id}", new MvcRouteHandler())
 {
   Defaults = new RouteValueDictionary(new { controller = "Home", action = "Index", id = UrlParameter.Optional }),
   DataTokens = rootNamespace
 }); 

“rootNamespace”在哪裡

var rootNamespace = new RouteValueDictionary(new { namespaces = new[] { "MyApp.Web.Controllers" } });

LowercaseRoute 繼承自 Route 並且只是使所有路徑小寫。我也有一個這樣註冊的區域:

context.Routes.Add(new LowercaseRoute("admin/{controller}/{action}/{id}", new MvcRouteHandler())
 {
   Defaults = new RouteValueDictionary(new { action = "List", id = UrlParameter.Optional }),
   DataTokens = adminNamespace
 });

其中 adminNamespace 是另一個命名空間,與預設路由中的想法相同,但具有正確的命名空間。這很好用,我可以訪問如下所示的 URL:

http://example.com/contact  <- default route, "Home" controller
http://example.com/admin/account  <- area route, "Account" controller, default "List" action

問題是這

http://example.com/admin/home/contact

也有效。“管理”區域下沒有帶有“聯繫”操作的“家庭”控制器。它從“/contact”中提取正確的頁面,但 URL 為“/admin/home/contact”。

有什麼辦法可以防止這種情況發生嗎?

謝謝。

看一下 AreaRegistrationContext.MapRoute 的程式碼:

public Route MapRoute(string name, string url, object defaults, object constraints, string[] namespaces) {
   if (namespaces == null && Namespaces != null) {
       namespaces = Namespaces.ToArray();
   }

   Route route = Routes.MapRoute(name, url, defaults, constraints, namespaces);
   route.DataTokens["area"] = AreaName;

   // disabling the namespace lookup fallback mechanism keeps this areas from accidentally picking up
   // controllers belonging to other areas
   bool useNamespaceFallback = (namespaces == null || namespaces.Length == 0);
   route.DataTokens["UseNamespaceFallback"] = useNamespaceFallback;

   return route;
}

請特別注意UseNamespaceFallback令牌,它預設設置為 false。如果要將搜尋限制在區域的命名空間,則需要具有類似的邏輯。(True = 搜尋控制器的目前命名空間,搜尋所有命名空間失敗。False = 僅搜尋目前命名空間。)

引用自:https://stackoverflow.com/questions/4612279