【问题标题】:ASP.Net MVC 2 Area, SubArea and RoutesASP.Net MVC 2 区域、子区域和路由
【发布时间】:2011-03-17 19:14:47
【问题描述】:

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

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

我的路线注册按注册顺序排列,考虑 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:网站/Foo/Bar/Home 等...这当然是错误的。

当我删除 Foo/Bar 的区域注册时,一切都会再次起作用。直接转到网址网站/主页/关于或网站/主页确实会显示正确的页面,所以我猜测内部 UrlHelper 以某种方式选择了错误的渲染路线。

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

我觉得最奇怪的是删除 Foo/Bar 注册解决了这个问题。我希望有人能对这件事有所了解..

【问题讨论】:

  • 将注册更改为 Foo-Bar 而不是使用 / 没有区别..

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


【解决方案1】:

您需要了解的是,Area 只是一个路由概念,Microsoft 巧妙地封装了该概念或 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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-09
    • 1970-01-01
    • 1970-01-01
    • 2018-05-31
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    • 1970-01-01
    相关资源
    最近更新 更多