2017-01-13 45 views
3

我有什么似乎是一个常见的错误时,两个控制器具有相同的名称:ASP.NET MVC - 发现了多种类型的匹配控制器

多种类型的发现匹配名为“项目控制器”。 如果为请求 ('{controller}/{action}/{id}')提供服务的路由没有指定名称空间来搜索 以匹配与请求匹配的控制器,则会发生这种情况。如果是这种情况, 通过调用“MapRoute”方法 的过载来注册该路由,该方法采用'namespaces'参数。

关于 '相关' 的请求已发现以下的匹配控制器:

Stock.Controllers.ItemsController

Stock.Areas.Admin.Controllers.ItemsController

这是真实的作为我有两个控制器在不同的命名空间中使用这个名称(如上面错误中所述)。然而,我所见过的大多数修复都是将命名空间添加到默认的根目录,例如

routes.MapRoute(
     "Default", // Route name 
     "{controller}/{action}/{id}", // URL with parameters 
     new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults 
     new string[] { "Stock.Controllers" } 
    ); 

在我AdminAreaRegistration.cs文件所创建的默认路由:

context.MapRoute(
     "Admin_default", 
     "Admin/{controller}/{action}/{id}", 
     new { action = "Index", id = UrlParameter.Optional } 
    ); 

所以我尝试添加的命名空间这条路线,但是这并没有解决,要么如

context.MapRoute(
     "Admin_default", 
     "Admin/{controller}/{action}/{id}", 
     new { action = "Index", id = UrlParameter.Optional }, 
     new string[] { "Stock.Areas.Admin.Controllers" } 
    ); 

我保证AreaRegistration.RegisterAllAreas被称为e.g

protected void Application_Start() 
{ 
    AreaRegistration.RegisterAllAreas(); 
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
    RouteConfig.RegisterRoutes(RouteTable.Routes); 
} 

任何人都可以点东西,我丢失或暗示别的东西,我应该做的,以获得两个控制器的工作?

感谢

+0

这应该工作正常..你可以尝试重建项目或从bin文件夹中删除项目DLL并再次重试 –

+0

是啊,尝试了好几次没有运气,甚至从AdminAreaRegistration中的“调试”和“bin”文件夹 – ca8msm

+1

中删除了该文件.cs添加'controller =“Home”',重建解决方案并重试 –

回答

2

我发现,解决我的问题的方法,我不得不添加的应用程序的默认命名空间通过“ControllerBuilder.Current.DefaultNamespaces.Add”方法来启动事件:

protected void Application_Start() 
     { 
      AreaRegistration.RegisterAllAreas(); 
      FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
      RouteConfig.RegisterRoutes(RouteTable.Routes); 
      ControllerBuilder.Current.DefaultNamespaces.Add("Stock.Controllers"); // Add This 
     } 
+1

您可以标记你的答案被接受为答案。 – RedgoodBreaker

相关问题