How to create a 301 redirect with ASP.net?

Creating a 301 redirect as part of the server configuration is always the best solution. But if you only need to build a local redirection, only from one specific file of your server, it can be useful to make it in a scripting language such as Microsoft ASP.net, rather than configuring the whole server for an exceptional behaviour.

This page describes the few steps you'll need to follow in order to set up a 301 redirect using ASP.net language. In fact, the main steps of this process only consist of a two lines code you'll have to paste on top of the file you need to redirect. That's all.



Defining the 301 code and the target address.
As ASP.net is a server side language, it can easily compute some data even before any answer has been sent to the client browser from the server. Using this behaviour, and some adequate commands, it's then easy to dynamically write a new header for a request and define it as a 301.

To achieve this, first open the file from which you want to set up the redirection. This file must, of course, be an ASP.net file in order to be able to execute Active Server Pages code on your server. Then, copy the following code, as the very first lines of your ASP file, and replace the http://www.newlocation.com by the real destination address of your 301.

<%
private void Page_Load(object sender, System.EventArgs e)
{
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location","http://www.newlocation.com");
}
%>

In the ASP.net language, response object is used to define the answer of the server to a specific request, and so can be uses to define a 301 redirect. This way, the first information your client will receive is the relocation command. Obeying to the redirection code, it will not keep in consideration any line of the following page.



Dynamically defining the redirection target.
If the response object must be the first instruction to be sent to the client, it's not necessarly the first one to be executed by the server. Using ASP redirection, you are free to use any command you need before the response object setting, as long as you don't send any data to the client browser.


You can then easily imagine that the target address of the redirection is defined following attributes present in the original page address, session's values or any database entry. Storing this new address in an ASP variable is then easy, and reusing it in the response location is a matter of a single line modification:

Response.AddHeader='Location',NewLocation