301 permanent redirect in asp.net ?


In the next release of the .NET Framework (.NET Framework 4.0) there is a new response method for permanently redirecting a request: Response.RedirectPermanent.  You can see the Beta MSDN documentation for Response.RedirectPermanent here.  This will automatically issue the 301 moved permanently status code and redirect to the target page.  A permanent redirect status code tells a search engine to update their cache and reassign the old url to the new url.

But if you need to do this now (prior to .NET Framework 4.0) you will need to do it the manual way.  To do so you will need to manually add the status and location headers to the response.

The pre .NET Framework 4.0 versions are:

  Response.Status = “301 Moved Permanently”;
  Response.AddHeader(“Location”, “/”);

  Response.Status = “301 Moved Permanently”;
  Response.AddHeader(“Location”, “/”);
Response.End();

There is also a RedirectToRoutePermanent method which will allow you to redirect to a new url using route parameters (and sends the 301 Moved Permanently status code).

Another alternative that doesn’t rely on hard-coded strings:

Response.Redirect(newLocation, false);

Response.StatusCode = 301;

Response.End();

This will correctly expand the path, apply the app-path modifier if necessary, and URL-encode the new location.

It will also throw an exception if you use it from a call-back, correctly handle smart-navigation post-backs, and output the recommended “Object moved” HTML document in case the browser doesn’t follow the redirection.

 

Another even aproach would be this one:

public static class HttpResponseUtility {

public static void RedirectPermanent (

this HttpResponse response,

string url) {

response.RedirectPermanent(url, true);

}

public static void RedirectPermanent (

this HttpResponse response,

string url,

bool endResponse) {

response.Redirect(url, false);

response.StatusCode = 301;

if(endResponse){

response.End();

}

}

}

And there we’ve extended the HttpResponse in Asp.Net 3.5 with the new 4.0 methods.

Cheers,

Even a cleaner way if you don’t want to hardcode the number:

Response.Redirect(newLocation, false);

Response.StatusCode = (int)System.Net.HttpStatusCode.MovedPermanently;

Response.End();

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s