我已将所有管理 Controller 放在 Controller 文件夹中的 Admin 文件夹中。由于我的一个管理 Controller 与 Controller 文件夹中的另一个 Controller 的名称匹配,因此我收到以下错误。
Multiple types were found that match the controller named 'Product'. 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.
我尝试添加以下路由,但问题仍然相同
routes.MapRoute(
"", //Route name
"Admin/{controller}/{action}/{id}", // Url with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional });
我怎样才能摆脱这个错误。更改 Controller 的名称是我想到的最后一个选项。现在,我正在寻找一种方法来保留名称,看看我是否可以找到另一种方法来解决这个问题。
最佳答案
I have placed all my admin controllers inside an Admin folder in Controller folder
好吧,那是你的问题。给定以下请求 /admin/index
(Controllers 文件夹中的 Controller 或 Controllers/Admin 文件夹中的 on),您如何期望默认 Controller 工厂知道要实例化哪个 Controller ?请记住,默认 Controller 工厂会在派生自 Controller 的已加载程序集中搜索类型。它并不真正关心它们是在哪个文件夹中声明的。因此,当它发现您有 2 个名称相同的 Controller 时,它不知道该选择哪一个。
一种可能性是使用区域。然后你可以在注册路由时指定命名空间:
routes.MapRoute(
"",
"Admin/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "AppName.Areas.Admin.Controllers" }
);
同样在您的 Global.asax 中确保为非区域 Controller 指定 namespace :
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "AppName.Controllers" }
);
关于c# - 为管理 Controller 添加路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8471612/