If we use same name controller in Area and Root in Asp.Net MVC application than we will conflict and throw an error like below.
~/Controllers/HomeController.cs
~/Areas/Blog/Controllers/HomeController.cs
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
.To resolve it we have to provide the proper namespace when creating route for both.
For the root controller we have to define route in Global.asax file. Route will be looked like below.
routes.MapRoute(
"default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "ApplicationName.Controllers" }
);
And for the Area controller, we have to define route in BlogAreaRegistration.cs which is inside in Area/Blog
context.MapRoute(
"Blog_default",
"Blog/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "ApplicationName.Areas.Blog.Controllers" }
);
Conclusion:
So, today we learned how to use same name controller in root directory of application and as well as inside area.
I hope this post will help you. Please put your feedback using comment which helps me to improve myself for next post. If you have any doubts please ask your doubts or query in the comment section and If you like this post, please share it with your friends. Thanks
Bellash Posted : 6 Years Ago
Good tip. I would like to add this code, in case you use named parameters. ` routes.MapRoute( name: "DeepRoutes", url: "{controller}/{action}/{id}", defaults: new { controller="home",action = "index" }/*, constraints: new { id = "{id::}"}*/, namespaces: new string[] { "i7.web.Controllers" } ); `