4

I have a HttpModule which intercepts all requests and loads data from the database based on routing rules. However, I run into one problem all the time; GetRouteData only works if the path does not exist:

var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(HttpContext.Current));

Assuming a request comes in for the url http://localhost/contact, I get the correct routing data relating to that url if that path does not exist in the file system. The problem appears when I want to customize the page at that url which I do by creating an aspx page in the path ~/contact/default.aspx. Once I do that, GetRouteData return null.

I have even tried creating a new HttpContext object, but I still can not retrieve route data if the page exists.

Has anyone ever run into this problem? Is there a solution/workaround?

All help will be greatly appreciated.

Alfero Chingono
  • 2,663
  • 3
  • 33
  • 54

1 Answers1

3

Set RouteCollection.RouteExistingFiles to true.

public static void RegisterRoutes(RouteCollection routes)
{
    // Cause paths to be routed even if they exists physically
    routes.RouteExistingFiles = true;

    // Map routes
    routes.MapPageRoute("...", "...", "...");
}

Beware though. IIS7 behaves a little differently than the server used when debugging within Visual Studio. I got bit by this when I deployed my application to the web. Check out this feedback I submitted to Microsoft Connection.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
  • Hmmm, very helpful indeed! That certainly solved my problem, but unfortunately creates a new problem. When I do that, all my css, js and image files get routed through my routing rules which is not really what I want. I still want the existing files to use the original handler except I just want to obtain the routing values. Is that possible? – Alfero Chingono May 02 '11 at 00:13
  • That problem isn't created by routing existing files. It's a separate issue that results from URL routing. I'm sorry, I'm not sure what you mean about you just want to obtain the routing values. – Jonathan Wood May 02 '11 at 00:17
  • Let take for example that I have a "Contact Us" page and I want it to display content from the database as well as a form to submit contact information. If the "Contact Us" page does not exist, I can call: `var pageName = RouteTable.Routes.GetRouteData(new HttpContextWrapper(HttpContext.Current)).Values["name"];` and retrieve data relating to that page from the database. However, when the page exists, I can not do that since `GetRouteData` returns null. Makes sense? – Alfero Chingono May 02 '11 at 00:27
  • 1
    I figured it out... Had to add route constraints. – Alfero Chingono May 02 '11 at 00:36
  • 1
    Good, because I was still having a little trouble understand what you were doing, or why. :-) – Jonathan Wood May 02 '11 at 00:40