2

In my web application "subsites" and pages are created on the fly. Routes are added the RouteTable.Routes whenever a new subsite is created, or (sometimes) when a new page is created. Something like this:

public static Site RegisterSite(Site site) {
    DeregisterSite(site);

    // Register non-auto-routed pages first so the default route doesn't override them.
    foreach (SitePage page in site.SitePages.Where(o => !o.IsAutoRouted))
        RegisterPageRoute(site, page);

    RegisterDefaultRoute(site);

    return site;
}

// Both RegisterPageRoute and RegisterDefaultRoute eventually make it here...
private static Route RegisterRoute(int siteId, string routeName, Route route) {
    using (RouteTable.Routes.GetWriteLock()) {
        RouteTable.Routes.Add(routeName, route);
    }

    return route;
}

I've debugged the creation of a new site and when the site is created, the route is registered correctly (RouteTable.Routes includes the new routes). If I then attempt to browse to the URL(s) which would be served by the new route(s), they never make it to the controller which is supposed to serve them -- I get a hard IIS error page:

The resource cannot be found.

So, if the routes are being added, why aren't they being "seen" when the MVC framework receives a request for one of the new routes? Am I missing a step somewhere? Do I need to tell the MVC framework to "reload" the route table?

Josh M.
  • 26,437
  • 24
  • 119
  • 200

1 Answers1

0

In my case, routes were being added in this order:

  1. Site-based routes (very specific)
  2. Root home page (not specific)

So routing worked correctly, on first load, but new routes were being added to the end of the route table, after the non-specific "other routes". So, that non-specific route was picking up all requests once it was hit.

The solution is simple, either:

  1. Don't create non-specific routes, or
  2. Rebuild the entire route table in the proper order when new sites/pages are added, or
  3. Make sure new site/page routes are added to the top of the route table: RouteTable.Routes.Insert(0, newRoute)
Josh M.
  • 26,437
  • 24
  • 119
  • 200