Saf*_*nes 2 c# model-view-controller asp.net-mvc asp.net-mvc-5.2
问题
对于默认路由,MVC返回"找到与名为'admin'的控制器匹配的多个类型." 错误而不是找不到404.该命名空间中没有管理员控制器.
我们正在使用MVC 5.2.2.
背景
我们正在使用MVC领域.两个区域包含"admin"控制器.当您使用各自路径中定义的完整路径时,两个区域的管理控制器都可以访问并正常工作.
当您尝试从默认路由访问"admin"时出现问题.管理员在该上下文中不存在,因此我们期望找不到404,但是我们会收到:
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
Run Code Online (Sandbox Code Playgroud)
这是我们的默认路线和两条区域路线:
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" }
);
}
Run Code Online (Sandbox Code Playgroud)
/ Stock/Admin/Index工作正常.
/库存/管理员/索引正常工作.
/ Admin /无法正常工作(期望:找不到404,收到"多个控制器"错误).
错误表明我们在路由中添加了名称空间,但正如您在上面所看到的,默认区域和两个区域都已经有了名称空间定义.默认路由指向名称空间,其中没有任何"admin"控制器.
我认为MVC试图通过搜索可能匹配请求的URL的可能控制器来"有用".有什么方法可以把它关掉吗?
我自己能够解决这个问题.这是我找到的解决方案:
// 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;
Run Code Online (Sandbox Code Playgroud)
注意添加.DataTokens ["UseNamespaceFallback"] = false; 这就解决了这个问题.关于这个功能的文档并不多(任何?),但我在阅读MVC源代码时发现了它,特别是在DefaultControllerfactory(本期的来源)中.
在您知道Google的"UseNamespaceFallback"之后,您可以找到一些博客帖子和问题,其中人们遇到了类似的问题,并以同样的方式解决了问题.但是我在这个DataToken上找不到MSDN文档.
| 归档时间: |
|
| 查看次数: |
359 次 |
| 最近记录: |