Solution Structure

Solution Structure

By convention, ASP.NET MVC applications use HomeController to refer to the controller that handles requests made to the root of the application.  This is configured by default with the following route registration:

If you decide to partition your application using the ASP.NET MVC Areas feature, it’s not unusual that you would want calls to the root of each area to be handled using a similar convention, via a HomeController.  However, if you add a HomeController to an area (for instance, an Admin area), you may find yourself faced with this exception:

Multiple types were found that match the controller named ‘Home’. This can happen if the route that services this request (‘{controller}/{action}/{id}’) does not specify namespaces to search for a controller that matches the request. If this is the case, register this route by calling an overload of the ‘MapRoute’ method that takes a ‘namespaces’ parameter.

The request for ‘Home’ has found the following matching controllers:
AreaDemo.Areas.Admin.Controllers.HomeController
AreaDemo.Controllers.HomeController

Unfortunately by default you cannot have duplicate controller names in ASPNET MVC Areas (or between an Area and the root of the application). Fortunately, the fix for this is pretty simple, and the exception describes the step you need to take.  Once you’ve added an Area, you will have two different places (by default) where routes are defined: one in your root application and one in your area registration.  You will want to adjust both of them to specify a namespace parameter.  The root registration will change to something like this:

Likewise, within the AdminAreaRegistration.cs class, the default RegisterArea method looks like this:

To adjust it to support a default HomeController and namespaces, it should be updated like so:

With these changes in place, you should now be able to support the HomeController convention within your MVC Areas, with duplicate controller names between areas and the root of the application.

Happy coding!

 

The following two tabs change content below.

Steve Smith

Chief Technology Officer at Falafel Software
Steve Smith is an experienced software developer, architect, speaker, trainer, author, and entrepreneur. He has been developing web-based software using primarily Microsoft technologies since 1997. He has been a Microsoft MVP since 2000 (for ASP.NET) and a Microsoft Regional Director since 2005. Steve has a passion for software craftsmanship, and has published numerous courses for Pluralsight intended to help software developers improve their skills.​ More about me