gpt4 book ai didi

c# - ASP.NET MVC - 找到与 Controller 匹配的多种类型

转载 作者:行者123 更新时间:2023-11-30 16:45:42 25 4
gpt4 key购买 nike

当两个 Controller 同名时,我遇到了一个常见的错误:

Multiple types were found that match the controller named 'Items'. 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 'Items' has found the following matching controllers:

Stock.Controllers.ItemsController

Stock.Areas.Admin.Controllers.ItemsController

这是真的,因为我在不同的命名空间中有两个具有此名称的 Controller (如上面的错误中所命名)。但是,我看到的大多数修复都是将命名空间添加到默认根,例如

    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 被调用,例如

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

任何人都可以发现我遗漏的东西或建议我应该做些什么来让两个 Controller 正常工作吗?

谢谢

最佳答案

我找到了解决我问题的方法,我必须通过“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
}

关于c# - ASP.NET MVC - 找到与 Controller 匹配的多种类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41632781/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com