Wednesday, December 8, 2010

How to do a 301 redirect in ASP.net for permanently moved resources - Global.asax code changes

If you are here, you might already be knowing that 301 redirect is the standard way of telling your clients (browsers, usually) that a server resource or a page has been permanently moved to a new location. Since most search engines respect this code, they will make sure that your 301 redirects are duly noted in their indexes which results in accurate search results.

Here is one raw way of implementing this, using Global Application Class (Global.asax) file.

Pre-requisites
I'm assuming that you have a Global.asax file  in your specific ASP.net project. If don't, add it as a New Item. It will have already a place to handle Application level errors. The below code is the code, where you're going to implement the changes.

 void Application_Error(object sender, EventArgs e)
    {
        // Code that runs when an unhandled error occurs

    }
The Logic:
The idea is to trap the 404 error (this will occur since the requested page does not exists) and provide appropriate 301 redirect request as the output. The below code does just that. Refer inline comments for more information on what each line of code means.

The Sample Code:

void Application_Error(object sender, EventArgs e) 
    { 
        // Code that runs when an unhandled error occurs
        // retrieve the last server error
        HttpException he = (HttpException)Server.GetLastError();
        // check for 404 error
        if (he.GetHttpCode() == 404)
        {
            // implement the logic to decide whether redirect is needed
            if (Request.RawUrl.ToLower().Contains("oldpage.aspx"))
            {
                Server.ClearError(); // clear the existing server error, good to have for additional processing
                Response.Clear(); //clears the response cache, if some information already exists
                Response.Status = "301 Moved Permanently"; // set the 301 status header
                Response.AddHeader("Location", "newpage.aspx"); // set the redirect location
                Response.End();
            }
            
        }
    }

For simplicity sake, additional checks are avoided in the above code.

If more flexibility and control is needed, look for a good URL rewriter for ASP.net.

In case, if you're wondering what a Response.Redirect does, it's just a 302 redirect that says that the resource is found at another location, which is treated as a temporary redirect. For more information, refer the HTTP Status Codes at http://en.wikipedia.org/wiki/List_of_HTTP_status_codes

No comments:

Post a Comment