c# - 为管理 Controller 添加路由

标签 c# asp.net-mvc-3 asp.net-mvc-routing

我已将所有管理 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/

相关文章:

c# - 我应该通过 RedirectToAction 还是 TempData 传递值?

asp.net-mvc-routing - MVC5 : Attribute Routing Precedence Among Controllers

c# - 无法使用 Nuget Package Restore 将 Newtonsoft.Json 从 10.0.1 更新到 10.0.2

c# - 使用 Mono 5 编译包含 ValueTuple 的 C# 7 代码

c# - ASP.NET MVC3 C# : Passing query as a parameter and displaying result

JavaScript 组合压缩插件/解决方案

c# - @Html.Action MVC 4 带有 QueryString 参数

c# - ASP.NET MVC 3 - 区域路由的边缘案例

c# - Log4net 生成错误的日志文件名

c# - RestSharp 简单完整示例