Nicolas De Irisarri
Nicolas De Irisarri

Reputation: 1077

Multiple default controllers for a route

short question:

Is there a way to configure multiple default controllers in a route??

Long explanation:

I am creating something similar to a portable area in MVC 5. Specifically, I want to create a kind of default controller that will be fired from my portable component if the user does not create it in his application. To be more precise:

I was able to create the default controller in the framework, and hook it up correctly, but it will not fall back. This is what routeDebugger is showing me: routes

As you see I have both routes configured (same URL, different defaults). What I am expecting would be: if controller Home does not exist, then FrameworkHome should be called.

I have played with the namespaces, but the result is the same.

Any clue on how to do this?

Upvotes: 1

Views: 791

Answers (1)

Daniel J.G.
Daniel J.G.

Reputation: 34992

You could solve this using a single route and prioritizing the controllers in the application namespace over the controllers in the framework namespace.

Let´s say the application controllers are defined in the namespace MyApplication.Controllers and the framework controllers are defined in the namespace Framework.Controllers.

For the root url / you want the application to match the controller:

  • MyApplication.Controllers.HomeController if defined

  • Otherwise the controller Framework.Controllers.HomeController (note this is also named HomeController and not FrameworkHomeController, however it is defined in the framework namespace)

This is achieved with a single default route:

routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    namespaces: new[] { "MyApplication.Controllers" }                
);

Tha namespaces defined in the route are given priority when multiple matching controllers are found. So for the root url / the default controller name Home is used, and if the system finds 2 controllers MyApplication.Controllers.HomeController and Framework.Controllers.HomeController then the one in the namespace MyApplication.Controllers will be used.

Upvotes: 1

Related Questions