MVC, Dynamic routing, Unity, Determine if current controller exists in global.asax
Question
What I'm trying to do is dynamic routing for my application.
For instance, in Application_BeginRequest() I want to get the current controller and determine if it exists. If not, I want to add a set of routes that override the default routing so that my url looks like this
mysite.com/term from database
But, if the "term from database" is a valid controller, I want it to use the default routing
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
I already have my routes the way I want. Now I just need to get the current controller and determine if it exists. If I do not add my custom routes, I recieve this error:
The IControllerFactory 'MySite.Web.UnityControllerFactory' did not return a controller for a controller named 'term from database'.
Is there a way to use unity from the global to determine if the controller exists?
Thanks!
Solution
Why don't you create a utility helper class that registers routes from your database and then apply your controller routes in your global.asax?
As your DB routes are registered first, if it finds a valid route then it would use that one first. Or you could set it vice versa. As an extra note I would make sure your routes from your DB have an associated RouteName to avoid conflicts.
public class Global : HttpApplication { public static void RegisterRoutes(RouteCollection routes) { //call utility to register routes from db RouteHelper.RegisterRoutesFromDB(routes); //now define my standard routes routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" } ); ...
OTHER TIPS
here is a solution. Using that, you can define alternative routes for each route as follow
var defaultRoute = routes.MapReplaceableRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id =
UrlParameter.Optional }
);
var route = routes.MapRoute(
name: "Dynamic",
url: "{name}",
defaults: new { controller = "Dynamic", action = "Index" });
defaultRoute.AlternativeRoute = route;