ASP.NET MVC Whole Site 301 Permanent Redirect

For some reasons, we need to permanently redirect the whole website to another website. It would be much easier that you are the owner of the server. But most of time you just host your website on the server out there. It wouldn’t be a big problem that your hosting company will support you to do some simple 301 redirect or may you have enough privilege to do it yourself. Is it possible to redirect permanently the website to other website by programming a little bit?

Sure you can. With MVC routing facilities, you can define your customized redirect logic: CREATE AN EMPTY MVC PROJECT, MODIFY GLOBAL.ASPX.CS FILE ONLY ON THIS EXAMPLE:

First of all, define two objects which implemented IRouteHandler and IHttpHandler, you can feel free to define those two objects on Global.aspx.cs file:

//@Implements IRouteHandler
class RedirectRouteHandler : IRouteHandler
{
private string newUrl;
public RedirectRouteHandler(string newUrl) { this.newUrl = newUrl; }
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return new RedirectHandler(newUrl);
}
}

//@object implements IHttpHandler
class RedirectHandler : IHttpHandler
{
private string newUrl;

public RedirectHandler(string newUrl) { this.newUrl = newUrl; }

public bool IsReusable { get { return true; } }

public void ProcessRequest(HttpContext httpContext)
{
httpContext.Response.Status = “301 Moved Permanently”;
httpContext.Response.StatusCode = 301;
httpContext.Response.AppendHeader(“Location”, newUrl);
return;
}
}

Then add one line on RegisterRoutes(RouteCollection routes) method (in Global.aspx.cs):

routes.Add(new Route(“{*pathInfo}”, new RedirectRouteHandler(@”http://koumei.net”));

Now all request to the website will redirect to “koumei.net” permanently. :)

One thought on “ASP.NET MVC Whole Site 301 Permanent Redirect”

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">