It is fairly common that you will need to configure a page in your web application to redirect a user to another page. The reasons for this vary, but in one specific case you may want to rethink how you are redirecting your users. When a call to Response.Redirect() is made, the server sends a response back to the client with an HTTP 302 status code, telling the client that the resource has temporarily moved and where it can find the resource.
I've created a simple page, OldPage.aspx, which redirects to NewPage.aspx during the Page_Load event. Let's jump into FireBug and see exactly what our response and redirect looks like.
This is not a big deal for the average Joe browsing your site, but when a search engine hits your page and sees that code, your new page's search engine rank could take a hit. An HTTP 302 status code means that the resource has temporarily moved, and when a search engine sees this it will attribute the content of the new page with the old URI. This makes perfect sense: if your page has only temporarily moved, there is no reason for a search engine to associate the content with the "temporary" page.
So at this point you might be asking yourself, how do we tell the search engine that the page has permanently moved? Well, you would need to return an HTTP 301 status code from the page. But since the Response.Redirect() method handles the status code internally, what options are left to correct this problem? Enter the HttpHandler.
HttpHandlers allow us to plug directly into the ASP.NET request pipeline. You can create a single HttpHandler that handles many different types of requests (for example, all requests to .aspx resources are handled by an HttpHandler), or one that handles a specific request for a resource. In our case, we'll choose to create an HttpHandler that specifically handles requests for our page.
To get started, you need to create a class that inherits the IHttpHandler interface. This interface requires that you implement two members: the IsReusable property and the ProcessRequest method. Here is a quick explanation of each.
In this example, we will create a class called RedirectHandler. We'll set the IsReusable property to false and add code in the ProcessRequest method to set the status code of the Response object and to add to it a header which will contain the location of the moved resource.
That is about as easy as it gets when it comes to creating custom HttpHandlers. The only thing left to do is register the new HttpHandler in our web.config so that our application knows to process incoming requests for OldPage.aspx using the RedirectHandler class.
Now armed with our new HttpHandler, let's jump back in to FireBug and see what our response and redirect look like now.
As you can see, the correct HTTP status code (301) is being returned and we have properly communicated our intentions to any search engine that visits our site.