简体   繁体   中英

ASP.NET MVC - Multiple types were found that match the controller

I have what seems to be a common error when two controllers have the same name:

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

And this is true as I do have two controllers with this name in different namespaces (as named in the error above). However, most of the fixes I've seen for this is to add the namespace to the default root eg

    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" }
    );

In my AdminAreaRegistration.cs file the default route that was created was:

    context.MapRoute(
        "Admin_default",
        "Admin/{controller}/{action}/{id}",
        new { action = "Index", id = UrlParameter.Optional }
    );

So I tried adding the namespace to that route, but that didn't fix it either eg

    context.MapRoute(
        "Admin_default",
        "Admin/{controller}/{action}/{id}",
        new { action = "Index", id = UrlParameter.Optional },
        new string[] { "Stock.Areas.Admin.Controllers" }
    );

I've ensured that AreaRegistration.RegisterAllAreas is being called eg

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

Can anyone spot something that I'm missing or suggest something else that I should be doing to get both controllers working?

Thanks

I found a method that solved my problem, I had to add the default namespace on the application start event via the "ControllerBuilder.Current.DefaultNamespaces.Add" method:

protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            ControllerBuilder.Current.DefaultNamespaces.Add("Stock.Controllers"); // Add This
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM