routemagic icon indicating copy to clipboard operation
routemagic copied to clipboard

RouteMagic redirection giving 404 instead of redirecting

Open MrYossu opened this issue 9 years ago • 4 comments

Hello,

I have rewritten an old WebForms site in MVC5 (Visual Studio 2013 Ultimate Update 4, Windows 7 64-bit), and want to add permanent redirection from the old URLs to the new. Reading your blog post about RouteMagic (http://haacked.com/archive/2011/02/02/redirecting-routes-to-maintain-persistent-urls.aspx/), I thought this would do the trick.

I added the NuGet package, and then added the following to the end of the RegisterRoutes() method in the RouteConfig class...

routes.Redirect(r => r.MapRoute("old", "Default.aspx")).To(routes.MapRoute("new", "Home"));

However, if I try to access http://localhost:8109/Default.aspx, I just get a 404 in the browser. It doesn't redirect at all.

What am I doing wrong? I reproduced the problem on a brand new, out-of-the box MVC project. I just added your package and the one line of code shown above.

Thanks for any help you can give.

MrYossu avatar Jun 24 '15 12:06 MrYossu

Did you confirm that there is no Default.aspx on disk?

haacked avatar Jun 24 '15 21:06 haacked

Yup. This was a brand new MVC project.

MrYossu avatar Jun 24 '15 21:06 MrYossu

My guess is that another route is matching the request first so you're not running into the redirect route. In the default MVC project, the default route matches everything. So the redirect route needs to go first.

The following approach works in a brand new MVC 5 project.

using System.Web.Mvc;
using System.Web.Routing;
using RouteMagic;

namespace RouteDemo
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.Redirect(r => r.MapRoute("old", "Default.aspx"))
                .To(routes.MapRoute("new", "Home/{action}", new { controller = "Home", action = "Index" }));

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

For future reference, you can install the RouteDebugger package and it'll show you which routes are matching.

Install-Package RouteDebugger

It's useful for figuring out these types of routing problems.

haacked avatar Jun 25 '15 05:06 haacked

Thanks for the info. I'll have a look. I don't remember where I put the default route, so it could be that it was was before the redirect route.

Thanks also for the info about the package. I was wondering how you are supposed to debug routing!

MrYossu avatar Jun 25 '15 12:06 MrYossu