asp.net-mvc 在我的项目中遇到多个同名控制器的问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5092589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:55:49  来源:igfitidea点击:

Having issue with multiple controllers of the same name in my project

asp.net-mvcasp.net-mvc-3asp.net-mvc-areas

提问by mattruma

I am running into the following error with my ASP.NET MVC 3 project:

我的 ASP.NET MVC 3 项目遇到以下错误:

Multiple types were found that match the controller named 'Home'. This can happen if the route that services this request ('Home/{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 'Home' has found the following matching controllers: MyCompany.MyProject.WebMvc.Controllers.HomeController MyCompany.MyProject.WebMvc.Areas.Company.Controllers.HomeController

找到了多种与名为“Home”的控制器相匹配的类型。如果为此请求提供服务的路由 ('Home/{action}/{id}') 没有指定命名空间来搜索与请求匹配的控制器,就会发生这种情况。如果是这种情况,请通过调用采用“命名空间”参数的“MapRoute”方法的重载来注册此路由。

对“Home”的请求已找到以下匹配的控制器:MyCompany.MyProject.WebMvc.Controllers.HomeController MyCompany.MyProject.WebMvc.Areas.Company.Controllers.HomeController

I have a HomeController in my default controller folder, with a class name of MyCompany.MyProject.WebMvc.Controllers.HomeController.

我的默认控制器文件夹中有一个 HomeController,类名为 MyCompany.MyProject.WebMvc.Controllers.HomeController。

My RegisterRoutes method, in my global.asax, looks like:

我的 Global.asax 中的 RegisterRoutes 方法如下所示:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );
    }

I then have an area called Company, with a HomeController in the default controller folder for the area, with a class name of MyCompany.MyProject.WebMvc.Areas.Company.Controllers.HomeController.

然后,我有一个名为 Company 的区域,该区域的默认控制器文件夹中有一个 HomeController,类名为 MyCompany.MyProject.WebMvc.Areas.Company.Controllers.HomeController。

The RegisterArea method in the CompanyAreaRegistration file looks like:

CompanyAreaRegistration 文件中的 RegisterArea 方法如下所示:

   public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "Company_default",
            "Company/{controller}/{action}/{id}",
            new { area = "Company", action = "Index", id = UrlParameter.Optional }
        );
    }

This is all leading the error I highlighted at the beginning of this post. I am struggling trying to piece together a solution from various other posts, with NO LUCK.

这都是导致我在本文开头强调的错误的原因。我正在努力尝试从其他各种帖子中拼凑出一个解决方案,但没有运气

Is it possible to have a HomeController in the default controllers folder and then one in EACH area? If so, do I need to make (assuming I do) changes to my configuration file to make this work?

是否可以在默认控制器文件夹中放置一个 HomeController,然后在每个区域中放置一个?如果是这样,我是否需要(假设我这样做)更改我的配置文件才能使其正常工作?

Any help would be much appreciated!

任何帮助将非常感激!

回答by David Ruttka

The error message contains the recommended solution: "If this is the case, register this route by calling an overload of the 'MapRoute' method that takes a 'namespaces' parameter."

错误消息包含推荐的解决方案:“如果是这种情况,请通过调用采用 'namespaces' 参数的 'MapRoute' 方法的重载来注册此路由。”

routes.MapRoute(
     "Default", // Route name
     "{controller}/{action}/{id}", // URL with parameters
     new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
     new string[] { "MyCompany.MyProject.WebMvc.Controllers"}
);

This will make http://server/go to your HomeController's Index action which is, I think, what you want. http://server/company/homewill go to the Company area's HomeController's Index action, as defined in the area registration.

这将使http://server/转到您的 HomeController 的索引操作,我认为这是您想要的。http://server/company/home将转到 Company 区域的 HomeController 的 Index 操作,如区域注册中所定义。

回答by cooloverride

This is the asp.net mvc4 approach:

这是 asp.net mvc4 方法:

 routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "RegisterNow", id = UrlParameter.Optional },
            namespaces: new[] { "YourCompany.Controllers" }
        );

回答by Reynaldo

I had renamed the namespaces, so, i only deletede folders binand objand rebuild, work again.

我重命名了命名空间,所以,我只删除文件夹binobj重新构建,再次工作。

回答by T Gupta

Another plausible cause of this issue could be found below:

可以在下面找到此问题的另一个可能的原因:

Multiple types were found that match the controller named 'Home'

发现多种类型与名为“Home”的控制器相匹配

回答by cracker

use this

用这个

routes.MapRoute(
            "Default",
            "{controller}/{action}/{id}",
            new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            new[] { "ProjectName.Controllers" }
        );

回答by Leonel Sanches da Silva

If you're using RazorGenerator, just informing the namespacesparameter could be not enough.

如果您使用 RazorGenerator,仅通知namespaces参数可能是不够的。

I got to solve adding the statement marked below at Global.asax.cs:

我必须解决添加下面标记的语句Global.asax.cs

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        ControllerBuilder.Current.DefaultNamespaces.Add("MyProject.Controllers"); // This one
    }

回答by glownet

Use only the name of the project:

仅使用项目名称:

Public Class RouteConfig
    Public Shared Sub RegisterRoutes(ByVal routes As RouteCollection)
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}")
        routes.MapRoute( _
            name:="Default", _
            url:="{controller}/{action}/{id}", _
            defaults:=New With {.controller = "Home", .action = "Index", .id = UrlParameter.Optional} _
           , namespaces:={"MvcAreas"})  
    End Sub

回答by XzaR

As Chris Moschini mention the namespaces parameter may not be enough if you have two areas with same controller name with different namespaces and the default none area route will return 500 server error.

正如 Chris Moschini 提到的,如果您有两个具有相同控制器名称但具有不同名称空间的区域,那么 namespaces 参数可能还不够,并且默认的 none area 路由将返回 500 服务器错误。

routes.MapRoute(
     "Default", // Route name
     "{controller}/{action}/{id}", // URL with parameters
     new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
     new string[] { "MyCompany.MyProject.WebMvc.Controllers"}
);

It "best" to override the default route handler and add this line:

“最好”覆盖默认路由处理程序并添加以下行:

RequestContext.RouteData.DataTokens["UseNamespaceFallback"] = false;

回答by Logan Miller

I had this issue after I added a reference to another project that had the same routes and the problem continued after I removed the reference.

我在添加对另一个具有相同路由的项目的引用后遇到了这个问题,并且在删除引用后问题仍然存在。

Resolved by deleting the .dll file of that added reference from the bin folder and rebuilding.

通过从 bin 文件夹中删除添加的引用的 .dll 文件并重建来解决。

回答by Eddie.Power_AU

Like many others, I had this problem after creating a new MVC template project from VS2017 menu, on building the project I would get the op's error message. I then used the answer https://stackoverflow.com/a/15651619/2417292posted earlier in this thread by cooloverridefor mvc4 projects. This still didn't fix my issue so I renamed my Home view folder and HomeController file to be the view folder Company/ and controller file CompanyController. This then worked for me, not a fix per say but a workaround if your not stuck on having the route Home/Index my other issue was I couldn't find the reference causing the error and due to my dev platform being Azure WebApplication vs a full VM with a complete file system and IIS settings to mess with.

像许多其他人一样,我在从 VS2017 菜单创建一个新的 MVC 模板项目后遇到了这个问题,在构建项目时我会收到操作的错误消息。然后,我使用了Cooloverride在本主题中早些时候发布的答案https://stackoverflow.com/a/15651619/2417292用于 mvc4 项目。这仍然没有解决我的问题,所以我将我的主视图文件夹和 HomeController 文件重命名为视图文件夹 Company/ 和控制器文件 CompanyController。这对我有用,不是每个人所说的修复,而是一种解决方法,如果您没有坚持使用 Home/Index 路线,我的另一个问题是我找不到导致错误的参考,并且由于我的开发平台是 Azure WebApplication vs a具有完整文件系统和 IIS 设置的完整 VM。