1
votes

How can I route requests to a default PageController for routes that do not map to a controller or action? But for routes that do match a controller or action, have those behave as normal, using ASP.NET MVC?

Basically I have a CMS backend that I have developed and I need to be able to inspect the route, to see if it matches a route for a page, stored in the database and if so, forward the request to the default PageController, which handles loading the pages content from the database. There are also CORE pages, that do have their own Controllers and Actions defined, and if you enter a route that doesn't match a pages route in the database, I need it to revert to the default behavior of ASP.NET MVC and look for the {controller}/{action}.

I have searched and searched online, with not much luck finding how I could do this. Any help would be greatly appreciated.

1

1 Answers

2
votes

Set your routes up so the ones for existing controllers and actions are first, then have a catchall that maps to your PageController:

    // More specific routes go here

    routes.MapRoute(
        null,                                              
        "{controller}/{action}/{id}",                           // URL with parameters
        new { action = "Index", id = UrlParameter.Optional },   // Don't put a default for controller here
        // You need to constrain this rule to all of your controllers, so replace "ControllerA" with an actual controller name, etc
        new { controller = "ControllerA|ControllerB|ControllerC" } 
    );

    routes.MapRoute(
        null,
        "{*path}",
        new { controller = "Page", action = "Index" }
    );

Anything that isn't matched by the first rule and any rules you put before it will fall back to your page controller, with the path in a path parameter on your index action method.