In previous articles, I have described the Routing System and how to create Route Constraints in your application. Now the time is to resolve the common error "multiple matching controllers were found" raised by the routing system when your application have more than one controller with the same name in different namespace.
Raised Error
Suppose you have HomeController with in two namespaces : Mvc4_RouteConstraints & Mvc4_Route. You have also registered a Default route for your application as shown below.
- routes.MapRoute(
- "Default", // Route name
- "{controller}/{action}/{id}", // Route Pattern
- new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Default values for parameters
- );
So when you will run your application then it will throw the error that the request for 'Home' has found the more than one matching controllers as shown below fig.
How to resolve it...
We can resolve this error by setting priority of the controllers. Suppose in the application HomeCOntroller defined in the Mvc4_RouteConstraints namespace has high priority than Mvc4_Route namespace controller. Let's do it.
- routes.MapRoute(
- "Default", // Route name
- "{controller}/{action}/{id}", // Route Pattern
- new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Default values for parameters
- new[] { "Mvc4_RouteConstraints"});
- );
In above code, I have added the Mvc4_RouteConstraints namespace as a string which told the MVC framework to look in the Mvc4_RouteConstraints namespace before looking anywhere else. Now, when you run your application, it will run successfully without any error.
If you want to give preference to a controller with in one namespace and all other controllers should also resolved in another namespace, you need to defined multiple routes as shown below.
- routes.MapRoute(
- "Default", // Route name
- "{controller}/{action}/{id}", // Route Pattern
- new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Default values for parameters
- new[] { "Mvc4_RouteConstraints"});
- );
- routes.MapRoute(
- "Default", // Route name
- "{controller}/{action}/{id}", // Route Pattern
- new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Default values for parameters
- new[] { "Mvc4_Route"});
- );
What do you think?
I hope you have got how to resolve ambiguous controller error by defining routes. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.