0

I can't get a catch all route to work in MVC. I have tried to implement what is shown in this question, but it does not work. I have a controller called OnlineController with an Index action. My RouteConfig.cs is set up like this:

        public static void RegisterRoutes(RouteCollection routes)
        {
             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
             routes.MapMvcAttributeRoutes();

             AreaRegistration.RegisterAllAreas();

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

            routes.MapRoute("RouteName", "{*url}", new { controller = 
                       "Online", action = "Index" });
         }

Browsing to the following URL

Blockquote http://mysite/online/something

gives a 404. Why is it not caught and redirected to the index action on the Online controller?

Community
  • 1
  • 1
Dave
  • 2,473
  • 2
  • 30
  • 55

1 Answers1

2

If you want to catch all routes you should delete "Default" route:

public static void RegisterRoutes(RouteCollection routes)
{
     routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
     routes.MapMvcAttributeRoutes();

     AreaRegistration.RegisterAllAreas();

     routes.MapRoute("RouteName", "{*url}", new { controller = "Online", action = "Index" });
}

Routes are chosen in the order they were mapped and your url matches "Default" route.

If you want to catch some routes for existing controllers and actions you can use your "Default" route, but with constraints:

public static void RegisterRoutes(RouteCollection routes)
{
     routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
     routes.MapMvcAttributeRoutes();

     AreaRegistration.RegisterAllAreas();

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

    routes.MapRoute("RouteName", "{*url}", new { controller = 
                   "Online", action = "Index" });
 }

Now, if you controller name is "Home" or "Home2" and action name is "Index" or "Index2" these routes will be handled by existing controllers and actions, if other names - by "Online" controller

Roman
  • 11,966
  • 10
  • 38
  • 47
  • Is there a way to do this, but still catch routes for controllers that already exist? – Dave May 12 '17 at 22:29