1

Is it possible to define routes in various parts of a website.

Example, if I wanted to break functionality of my website out into modules, and each module would define the routes it needs.

Is this possible? How?

codecompleting
  • 9,251
  • 13
  • 61
  • 102

2 Answers2

4

Consider using ASP.NET MVC's built-in Areas.

An "Area" is essentially your module, and Areas allow you to register routes for each specific area.

If you've not used them before there is an MSDN walkthrough here:

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

Essentially, you have a directory for each area, which contains all your area-specific controllers and views, and in the route of that directory you place a file that registers the routes for that particular area like so:

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 ...
     }
}

In global.asax.cs you need to register all these extra areas, along with your other primary routes:

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}
        );

    ...
}     
Scott
  • 17,127
  • 5
  • 53
  • 64
  • +1 - It took me 5 minutes to find a suitable link to post here about Areas, by then you beat me to it... :) Just for extra info: http://stackoverflow.com/questions/5243158/how-to-configure-areas-in-asp-net-mvc3 – AJC Aug 03 '11 at 21:37
  • @AJC Thanks. I feel guilty now, for stealing your thunder! But yes, I know what you mean. There's not an "official" link for Areas, as far as I can see. – Scott Aug 03 '11 at 21:40
2

You can put a DefineRoutes(RouteCollection routes) method in each module, then call them all in Global.asax.cs.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • and if to make it dynamic you can use reflection to scan the folders? – codecompleting Aug 04 '11 at 14:43
  • You can loop through `typeof(MyType).Assembly.GetTypes()` and find all types that implement an `IModuleInitializer` interface, or something like that. – SLaks Aug 04 '11 at 14:49