A simple redirect route handler for ASP.NET 3.5 routing

ASP.NET 3.5 Routing is a very powerful tool not just for registering routes for newer ASP.NET MVC applications but also for adding SEO friendly routes to older Webforms (ASPX) applications, or for routing multiple URLs to a single page. But that’s not all it can do. You can create your own IRouteHandler and then have complete control over what to do with any incoming HttpRequest.

Here for example is a way to do a permanent redirect when a given route is matched. To use it you might, for example, do:-

[csharp] routes.Add(new Route(“sample.aspx”, new RedirectRouteHandler(“/home/start”)));


Here is the RedirectRouteHandler that can turn any request into a 301 redirect for you:-

[csharp] /// \ /// Redirect Route Handler /// \ public class RedirectRouteHandler : IRouteHandler { private string newUrl;

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

public IHttpHandler GetHttpHandler(RequestContext requestContext) { return new RedirectHandler(newUrl); } }

/// \ /// \ Redirecting MVC handler\ /// \ public 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; } }


Note: I’m not saying this is the best or only way to handle this. You’ll want to look at Url Rewriting and the Application and Request Routing module for IIS7 in particular.

Wed Apr 21 2010 05:22:43 GMT-0700 (Pacific Daylight Time)

Disqus goes here