Search code examples
asp.neturl-rewritinghttphandlerhttpmodule

Map an asp URL to an aspx Http[Handler/Module]


We are rewriting an old site for a client, from Classic ASP to ASP.NET 4. The new site will be living at the same root URL as the old one once it is pushed live.

One stipulation though is this... the old site used to use a page such as article.asp?articleid=### to load content. The new site will be using something similar, but making use of ASP.NET Routing such as ~/articles/o/### (the 'o' is for 'old id').

I need to be able to catch requests to the old article.asp page and rewrite the url to the new article.aspx url.

My original thought was to handle this in the Application_BeginRequest. I remapped the .ASP extension to be handled by the same handler dll as .ASPX pages, and then added the following code to my Application_BeginRequest in my global.asax:

Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
    Dim ctx = HttpContext.Current, url = ctx.Request.RawUrl
    If Regex.IsMatch(url, "/article\.asp\?articleid=\d+") Then
        Dim oldid = Regex.Match(url, "(?:articleid=)(\d+)").Groups(1).Value
        Server.Transfer("~/articles/o/" & oldid)
    End If
End Sub

This did not work though. As this is right now, I need to have an actual article.asp in the path or else I get a 404 error (and even then it doesn't actually do anything, and just displays a blank page). This would work fine (assuming redirect code in the ASP page worked), except that they had 500 copies of article.asp each in their own sub-directory (breaking the whole point of a CMS model). They want to preserve the old urls in case someone clicks an old one from an email or bookmark.

I need to be able to map this file name to the new path, irregardless of the sub-directory it was in, as per the logic in my Application_BeginRequest above. What would be the proper way to do this? As global.asax isn't working, I'm assuming I need to either write an HttpHandler or HttpModule class, but I'm not sure which is the right way to go.

Running IIS on Windows Server 2003 R2.

Thanks!


Solution

  • Putting my above code in the Application_BeginRequest method of global.asax actually WAS a right place. The problem was one more missing setting in IIS. In the dialog where you remap .ASP to the ASP.NET handler, you also need to make sure to turn off the option for Verify that file exists. This completed the procedure, and my old pages now map to the corresponding new pages.