.
ASP.Net
Skip Navigation Links

Using Global.ASAX to redirect pages based on extension

In my recent article on converting all your .htm pages to .aspx I came across a little problem that went deeper than one might imagine.

My site needed to have 100% ASPX pages but there were some instances where references to .HTM pages were buried in code, on other people's site or even indexed by Google. It is obviously desirable that any such references remain live so that the dreaded 404 page isn't shown for pages that ought really to exist.

My conversion routine brutally ripped out .htm files, of which I had over one hundred and fifty, and converted them to the equivalent name but just with a .ASPX extension and possible wrapping of the head and body tags with ASP.Net master page content tags.

I decided that there would be no more .htm pages at-all or ever on my site so I had the option to not allow files of that sort to be requested or, if they were, to simply assume the same name with the .ASPX extension.

To do this I relied on the ASP.Net Application class that runs for each instance of your web which is opened on the server. The Global.ASAX file is an optional script that can contain code which is compiled by the server and provides extra functionality for errors or other things. A particularly useful aspect of the Global.ASAX is the ability to respond to certain events on your site.

I wanted to simply look at requests that arrived and, if any were for an .htm page, I could assumt that these came from off-site links or google search results and a bit of code in the BeginRequest handler of the Global.ASAX file would redirect automatically to the equivalent .aspx URI by rewriting the URL in the correct form. Here's the code:

    /// <summary>

    /// This compiles to an event handler which is called whenever a request is made on the site.

    /// </summary>

    /// <param name="sender"></param>

    /// <param name="e"></param>

    protected void Application_BeginRequest(object sender, EventArgs e)

    {

        HttpContext ctx = HttpContext.Current; //Get the current context...

        if (ctx.Request.RawUrl.Contains(".htm")) // all my htm files are lower case filenames. Yours may be different...

        {

            ctx.RewritePath(ctx.Request.RawUrl.Replace(".htm", ".aspx"));

        }

    }

 

 

Sponsored By
DaraizeTechnologies.com
Bob Powell

Create your badge

Copyright © Bob Powell 2000-2012.  All rights reserved.