.NET MVC routing on legacy ASP pages

When working on legacy ASP websites often you have to work with a directory full of .aspx files:

  1. about.aspx
  2. login.aspx
  3. logout.aspx
  4. shopping.aspx

With some architectures, the code behind calls into a front controller as follows:

Protected Overrides Sub OnLoad(ByVal eventArgs As System.EventArgs)
    MyBase.OnLoad(eventArgs)
    
    Dim frontController As New LegacyFrontController
    frontController.LoadPage("shopping.aspx")
End Sub

Thanks to MVC route controllers, we can refactor such websites and reduce the amount of .aspx files.

All we need to do is create a method to add the route from each page to a proxy page for the front controller. The key here is pass the page as a data token so that, when frontcontroller.aspx is executed, it knows about the specific page requested.

foreach (string page in pages)
{
    var dataTokenDictionary = new RouteValueDictionary
    {
        { "page", page }
    };
    
    routes.MapPageRoute("route_" + page, page + ".asp",
        "~/frontcontroller.aspx", false, null, null,
        dataTokenDictionary);
}

Then to hook this new proxy page into the front controller, you just have to append the .aspx file extension back to the data token.

Protected Overrides Sub OnLoad(ByVal eventArgs As System.EventArgs)
    MyBase.OnLoad(eventArgs)
    
    Dim frontController As New LegacyFrontController
    frontController.LoadPage(RouteData.DataTokens("page") + ".aspx")
End Sub

This technique is a good middleground along the road to refactoring the whole website to MVC Controllers. It provides a clean website directory and makes it easier to change the behaviour of the front controller across all pages.

csharp 

See also