【问题标题】:How to define routes in more than one location?如何在多个位置定义路线?
【发布时间】:2011-08-04 05:44:43
【问题描述】:

是否可以在网站的各个部分定义路由。

例如,如果我想将网站的功能分解为模块,每个模块都会定义它需要的路由。

这可能吗?怎么样?

【问题讨论】:

    标签: c# asp.net-mvc


    【解决方案1】:

    考虑使用 ASP.NET MVC 的内置 Areas

    “区域”本质上是您的模块,区域允许您为每个特定区域注册路线。

    如果您在此处有 MSDN 演练之前没有使用过它们:

    http://msdn.microsoft.com/en-us/library/ee671793.aspx

    基本上,每个区域都有一个目录,其中包含所有区域特定的控制器和视图,并且在该目录的路由中放置一个文件,该文件为该特定区域注册路由,如下所示:

    public class MyAreaRegistration : AreaRegistration
     {
         public override string AreaName
         {
             get { return "My Area"; }
         }
    
         public override void RegisterArea(AreaRegistrationContext context)
         {
             context.MapRoute(
                 "news-articles",
                 "my-area/articles/after/{date}",
                 new {controller = "MyAreaArticles", action = "After"}
                 );
    
             // And so on ...
         }
    }
    

    在 global.asax.cs 中,您需要注册所有这些额外区域以及其他主要路线:

    public static void RegisterRoutes(RouteCollection routes)
    {
        AreaRegistration.RegisterAllAreas();
    
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
        routes.MapRoute(
            "Products",
            "products/show/{name}",
                new {controller = "Products", action = "Show", name = UrlParameter.Optional}
            );
    
        ...
    }     
    

    【讨论】:

    • +1 - 我花了 5 分钟才找到一个合适的链接来在这里发布关于区域的信息,到那时你打败了我...... :) 只是为了获得更多信息:stackoverflow.com/questions/5243158/…
    • @AJC 谢谢。我现在很内疚,偷了你的雷!但是,是的,我知道你的意思。据我所知,Areas 没有“官方”链接。
    【解决方案2】:

    您可以在每个模块中放置一个DefineRoutes(RouteCollection routes) 方法,然后在 Global.asax.cs 中调用它们。

    【讨论】:

    • 如果要使其动态化,您可以使用反射来扫描文件夹?
    • 您可以遍历typeof(MyType).Assembly.GetTypes() 并找到所有实现IModuleInitializer 接口或类似接口的类型。
    猜你喜欢
    • 1970-01-01
    • 2014-05-01
    • 2016-03-14
    • 1970-01-01
    • 2017-06-11
    • 2012-10-01
    • 2016-10-16
    • 2013-07-13
    • 1970-01-01
    相关资源
    最近更新 更多