【问题标题】:Ambiguous Controller Names in ASP.NET MVCASP.NET MVC 中的模糊控制器名称
【发布时间】:2020-06-17 02:57:15
【问题描述】:

我尝试在我的项目中实现 Phil's Areas Demo

http://haacked.com/archive/2008/11/04/areas-in-aspnetmvc.aspx.

我在现有 MVC 项目中附加了 Areas/Blog 结构,但在我的项目中出现以下错误。

控制器名称Home在以下类型之间有歧义:

WebMVC.Controllers.HomeController
WebMVC.Areas.Blogs.Controllers.HomeController 

这就是我的Global.asax 的样子。

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

    routes.MapAreas("{controller}/{action}/{id}",
        "WebMVC.Areas.Blogs",
        new[] { "Blogs", "Forums" });

    routes.MapRootArea("{controller}/{action}/{id}",
        "WebMVC",
        new { controller = "Home", action = "Index", id = "" });

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

}

protected void Application_Start()
{
    String assemblyName = Assembly.GetExecutingAssembly().CodeBase;
    String path = new Uri(assemblyName).LocalPath;
    Directory.SetCurrentDirectory(Path.GetDirectoryName(path));
    ViewEngines.Engines.Clear();
    ViewEngines.Engines.Add(new AreaViewEngine());
              RegisterRoutes(RouteTable.Routes);
   // RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes);

}

如果我从routes.MapAreas 中删除/Areas/Blogs,它会查看根的索引。

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:

    在 ASP.NET MVC 2.0 中,您可以在父区域中注册路由时包含父项目控制器的命名空间。

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

    这将路由限制为仅在您指定的命名空间中搜索控制器。

    【讨论】:

      【解决方案2】:

      使用 WebMVC.Areas.Blogs 和 WebMVC.Areas.OtherAreaName 代替 WebMVC.Areas.Blogs 和 WebMVC。将区域名称视为命名空间根,而不是绝对命名空间。

      【讨论】:

      • 我不确定我是否喜欢那个解决方案。项目的设计方式,主控制器/视图文件夹显然是它们自己的“区域”,它们只是没有指定的名称。我希望它继续按原样运行。
      • 如果您将路由配置为使用“main”作为默认区域,则可以这样做。
      【解决方案3】:

      你可以在多个同名控制器之间进行优先级路由,如下所示

      例如,我在Areas/Admin/HomeController 中有一个名为 HomeController 的控制器 另一个在根目录/controller/HomeController
      所以我按如下方式优先考虑我的根:

      routes.MapRoute(
          "Default", // Route name
          "{controller}/{action}/{id}", // URL with parameters
          new { controller = "Home", action = "Index", // Parameter defaults
          id = UrlParameter.Optional },
          new [] { "MyAppName.Controllers" } // Prioritized namespace which tells the current asp.net mvc pipeline to route for root controller not in areas.
      );
      

      【讨论】:

        猜你喜欢
        • 2010-10-18
        • 1970-01-01
        • 1970-01-01
        • 2011-02-12
        • 2011-03-01
        • 2016-01-25
        • 2011-01-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多