haacked / routemagic

Utility Library to get the most out of ASP.NET Routing.
MIT License
186 stars 46 forks source link

RouteMagic redirection giving 404 instead of redirecting #14

Open MrYossu opened 9 years ago

MrYossu commented 9 years ago

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.

haacked commented 9 years ago

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

MrYossu commented 9 years ago

Yup. This was a brand new MVC project.

haacked commented 9 years ago

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.

MrYossu commented 9 years ago

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!