I will soon move a web application to a different domain. Without any extra work this change will break the existing URLs. To prevent this from happening, I try a new approach with a small replacement application that accepts every request to the old domain name, logs its referring site and redirects the user after a few seconds to the new application.
The biggest challenge for this endeavour is to create a catch-all route configuration. You can replace all existing rules of the ASP.NET MVC 5 Template in the class RouteConfig with one that uses “{*url}” as the URL pattern:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Everything", "{*url}", new { controller = "Everything", action = "Index" } ); } } |
This rule will now redirect all requests to the Index() method of the EverythingController class. In this method we can log all the data we get from the Request object using the logging framework of our choice:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class EverythingController : Controller { // GET: Everything public ActionResult Index() { // use your logger to track outdated links: System.Diagnostics.Debug.WriteLine( $"Update link on page '{Request.UrlReferrer}' for '{Request.Url}'" ); return View(); } } |
In the view partial I can show a short explanation about the new URL and then do a redirect using JavaScript:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
@{ ViewBag.Title = "Index"; } <h2>This application has moved</h2> <p>Please update your bookmarks to the new location: <strong><a href="https://jgraber.net">JGraber.net</a></strong></p> <script type="text/javascript"> setTimeout(function() { window.location = "http://www.JGraber.net"; }, 5000); </script> |
With these three parts I can prevent the dreaded 404 errors without investing too much effort in keeping up the old structure. I think these little app will make the progression to the new domain a lot smoother.
Found exactly what I was looking for. Thank you for sharing this, keep sharing such clear and concise codes.
Thank you for sharing.
Adding [Route(“{*url}”)] attribute to your action would save you the RouteConfig component 😉
Hi Steffen,
Great point that reduces the code even more.
Thanks,
Johnny