Gal Segal's Blog

Thoughts of a programmer with a soul

Sep 21

MVC Routing Legacy URLs

Tags: ,

Premazzi_Luigi-ZZZ-Saddled_Horse_and_a_Horseman._Study1

When moving a web application from WebForms to MVC framework I found sometimes “.aspx” and “.ashx” URLs from the old website sniking into my new clean and carved URLs. This issue can be addressed¬†specifically by targeting the relevant “aspx” URLs and redirecting to a desired place, but it can get a bit messy. I found a more generic way of doing so by creating a new “Legacy Route” that will redirect all legacy requests to the new home page:

public class LegacyURLRoute : RouteBase
{
	public override RouteData GetRouteData(HttpContextBase httpContext)
	{
		var url = httpContext.Request.Url.AbsolutePath;
		if (url.Contains(".aspx") || url.Contains(".ashx"))
		{
			var response = httpContext.Response;
			response.Status = "301 Moved Permanently";
			response.RedirectLocation = "/";
			response.End();
		}
		return null;
	}

	public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
	{
		return null;
	}
}

I tend to place this route at the end of the route table to avoid the unnecessary checks:


RouteTable.Routes.Add(new LegacyURLRoute());

Back to top