MVC4 使用Areas后存在相同Controller时报错
报错如下:
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:
MVC.Controllers.HomeController
MVC .Areas.Search.Controllers.HomeController
问题原因:使用Areas后存在多个相同的Controller,路由注册未分开
解决方法:
修改SearchAreaRegistration文件 RegisterArea 方法如下
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Search_default",
"Search/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional },
new string[] { "MVC.Areas.Search.Controllers" }
);
}
修改RouteConfig文件内 RegisterRoutes 方法如下
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces:new []{" MVC .Controllers"}
);
}