Sunday, June 19, 2011

Add a Permanent 301 Redirect Route Using .Net Routing 3.5

As pages on our sites get old and replaced sometimes we need to redirect users to the newer pages.  You can do this in .Net Routing by setting up a new route which does a 301 (Permanent) redirect.

You will need a new route handler method to do the redirect.  The code for this is shown below:

/// <summary>
/// This route handler allows redirecting old urls to a new page/route name and 
/// sets a permanent 301 status code (Moved Permanently)
/// This can be invoked from the global.asax.cs like this:
///     The route below will redirect requests from somedirectory/A.aspx to somedirectory/login
///     routes.Add("OLDRoute1", new CustomRoute("somedirectory/A.aspx", new PermanentRedirectRouteHandler("login")));
/// </summary>
public class PermanentRedirectRouteHandler : IRouteHandler, IHttpHandler
{
    public PermanentRedirectRouteHandler(string virtualPath)
    {
        this.VirtualPath = virtualPath;
    }

    public string VirtualPath { get; private set; }
    private RequestContext requestContext = null;

    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        this.requestContext = requestContext;
        return this;
    }

    public bool IsReusable
    {
        get { return false; }
    }

    public void ProcessRequest(HttpContext context)
    {
        context.Response.StatusCode = 301;
        context.Response.AppendHeader("Location", VirtualPath);
    }
}

While testing you might want to change the StatusCode to 302 (temporary redirect).

To create a route using the PermanentRedirectRouteHandler method you would add a route like this:

Example 1:

routes.Add("OLDRoute1", new CustomRoute("A.aspx", new PermanentRedirectRouteHandler("login")));

The route above will redirect a request to ‘http://mydomain/A.aspx’ to ‘http://mydomain/login’.

Example 2:

routes.Add("OLDRoute2", new CustomRoute("site1/A.aspx", new PermanentRedirectRouteHandler("login")));

The route above will redirect a request to ‘http://mydomain/site1/A.aspx’ to ‘http://mydomain/site1/login’.

Example 3:

routes.Add("OLDRoute3", new CustomRoute("site1/B.aspx", new PermanentRedirectRouteHandler("/login")));

The route above will redirect a request to ‘http://mydomain/site1/B.aspx’ to ‘http://mydomain/login’.

Example 4:

routes.Add("OLDRoute4", new CustomRoute("contact-us", new PermanentRedirectRouteHandler("/login")));

The route above will redirect a request to ‘http://mydomain/contact-us/’ to ‘http://mydomain/login’.

As routes are evaluated in order you should add the redirect routes to the top of your routes in the Global.asax.

If you missed the first post in this series have a look at Adding .Net Routing 3.5 to Asp.Net Web Forms.

Happy Routing!

1 comment:

  1. Thank you for sharing such an informative article. I really hope I can see other interesting posts. Keep up the good work!


    Melbourne App Developer

    ReplyDelete