问题
对于默认路由,MVC 返回“找到与名为“admin”的 Controller 匹配的多种类型”。错误而不是 404 未找到。该命名空间中没有管理 Controller 。
我们正在使用 MVC 5.2.2。
背景
我们正在使用 MVC 区域。两个区域包含一个“管理” Controller 。当您使用各自路由中定义的完整路径时,两个区域的管理 Controller 都可以访问并正常工作。
当您尝试从默认路由访问“admin”时,就会出现问题。 Admin 在该上下文中不存在,因此我们预计会出现 404 not found,但我们收到的是:
Multiple types were found that match the controller named 'admin'. 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 'admin' has found the following matching controllers:
DMP.Stock.Web.Controllers.AdminController
DMP.Inventory.Web.Controllers.AdminController
这是我们的默认路线和两条区域路线:
public static void RegisterRoutes(RouteCollection routes)
{
// Default Route
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new string[] { "DMP.Core.Web.Controllers" }
);
}
public override void RegisterArea(AreaRegistrationContext context)
{
// Area 1: Stock
context.MapRoute(
name: "Stock_default",
url: "Stock/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new string[] { "DMP.Stock.Web.Controllers" }
);
}
public override void RegisterArea(AreaRegistrationContext context)
{
// Area 2: Inventory
context.MapRoute(
"Inventory_default",
"Inventory/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new string[] { "DMP.Inventory.Web.Controllers" }
);
}
/Stock/Admin/Index 工作正常。
/Inventory/Admin/Index 工作正常。
/Admin/无法正常工作(预计:404 未找到,收到“多个 Controller ”错误)。
这些错误表明我们将命名空间添加到路由中,但正如您在上面看到的,默认区域和两个区域都已经有命名空间定义。默认路由指向一个 namespace ,其中没有任何“管理” Controller 。
我认为 MVC 试图通过搜索可能与请求的 URL 匹配的 Controller 来“提供帮助”。有什么办法可以把它关掉吗?
最佳答案
我自己已经解决了这个问题。这是我找到的解决方案:
// Default Route
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new string[] { "DMP.Core.Web.Controllers" }
).DataTokens["UseNamespaceFallback"] = false;
注意添加 .DataTokens["UseNamespaceFallback"] = false;这就是解决问题的方法。关于此功能的文档并不多(任何?),但是我在阅读 MVC 源代码时发现了它,特别是在 DefaultControllerfactory (此问题的来源)中。
在您知道在 google 上搜索“UseNamespaceFallback”后,您可以找到一些博客文章和问题,人们在其中遇到了类似的问题并以相同的方式解决了它。但是我找不到关于此 DataToken 的 MSDN 文档。
关于c# - MVC 路由匹配无效的路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29350012/