ASP.Net MVC 2 Area,SubArea和Routes

时间:2010-07-19 08:13:54

标签: asp.net asp.net-mvc-2 routes asp.net-mvc-routing asp.net-mvc-areas

我一直在寻找解决问题的方法。发现了很多类似的问题,但没有一个能为我找到解决方案。

我正在尝试在区域内注册区域。这可行,但它“部分”搞砸了我的路由。

我的路线注册按照他们注册的顺序,考虑FooBar和Foo注册来自AreaRegistrations

 routes.MapRoute("FooBar_default",
           "Foo/Bar/{controller}/{action}",
           new { area = "Foo/Bar", controller = "Home", action = "Index"},
           new[] { BarHomeControllerType.Namespace }
  );

  routes.MapRoute("Foo_default",
            "Foo/{controller}/{action}/{id}",
            new { area = "Foo", controller = "Start", action = "Index", id = UrlParameter.Optional },
            new { controller = new NotSubArea()},
            new[] { typeof(StartController).Namespace }
        );

   routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

   routes.MapRoute("PagesRoute", "Pages/{action}", new { controller = "Pages", Action "Index" }).DataTokens["UseNamespaceFallback"] = false;

   routes.MapRoute("Default", // Route name
            "{controller}/{action}/{id}", 
            new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            new[] { typeof(HomeController).Namespace }
            ).DataTokens["UseNamespaceFallback"] = false;

现在出现以下问题。当使用以下网址正确生成这些页面中的Website / Foo /或Website / Foo / Bar链接时:

  !{Html.ActionLink<HomeController>(c => c.Index(),"Home", new { area = "Foo/Bar"})}
  or
  !{ Url.Action("Index", "Home", new { area = "Foo/Bar"}) } //or a different area

但是当我在我的主页中使用它时,换句话说就是网站/或网站/家庭等。

  !{Html.ActionLink<HomeController>(c => c.Index(),"Home", new { area = ""})}
  or
  !{ Url.Action("Index", "Home", new { area = ""}) } 
  //or with no area identifier specified

它会生成Url:Website / Foo / Bar / Home等...哪个是错误的。

当我删除Foo / Bar的区域注册时,它再次起作用。直接访问网站/主页/关于或网站/主页显示正确的页面,所以我猜猜内部UrlHelper正在选择错误的路线进行渲染。

我尝试切换FooBar_default和Foo_Default路由的顺序,以便在FooBar_default路由之前注册Foo_default路由,但随后该区域不再工作(找不到资源)并且链接仍然生成错误。

我发现最奇怪的是删除Foo / Bar注册可以解决问题。我希望有人能对这件事情有所了解......

1 个答案:

答案 0 :(得分:2)

你需要了解的是,一个区域只是一个路由概念,微软整齐地将这个概念包起来,或者UrlRouting让人们开始。

实际上,您可以根据自己的要求获取MVC框架来路由您的请求。

您可能需要做的是编写自己的RouteHandler。这将使您能够正确指导MVC框架如何根据您的要求路由任何请求。

请参阅this answerasp.net mvc complex routing for tree path作为示例,以帮助您入门。

chris166概述了我实施您自己的IRouteHandler,并将您的路线映射为使用它而应该能够满足您的需求。它比使用区域解决方案更省力,但应该会给你带来更好的结果。

routes.MapRoute(
    "Tree",
    "Tree/{*path}",
    new { controller = "Tree", action = "Index" })
            .RouteHandler = new TreeRouteHandler();
相关问题