【问题标题】:Using Areas, it doesn't seem to be able to figure out which controller I want [duplicate]使用区域,它似乎无法弄清楚我想要哪个控制器 [重复]
【发布时间】:2013-09-18 15:00:24
【问题描述】:

我很困惑,我创建了一个名为“Admin”的区域,我有这 2 个控制器:

/admin/users/...

/users/..

现在如果我尝试链接到这个网址:

/users/list

我收到此错误:

Multiple types were found that match the controller named 'User'. 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 

“命名空间”参数。

我很困惑为什么它不起作用,难道它不能确定这个 UserController 是不在区域中的那个吗?

【问题讨论】:

    标签: c# asp.net-mvc routes asp.net-mvc-areas


    【解决方案1】:

    您可以通过将命名空间设置为您的路线来解决此问题

    喜欢下面这个示例

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

    【讨论】:

    • 我不需要管理员定义,没有它就可以工作。
    • 未来也许你需要它!所以最好有它!
    【解决方案2】:

    当引入区域时,同名控制器之间可能会产生歧义 ref:http://haacked.com/archive/2010/01/12/ambiguous-controller-names.aspx

    尝试将其添加到您的 Global.asax

    public static void RegisterRoutes(RouteCollection routes)
    {
      //all your other routes
    
      routes.MapRoute(
        "Default",                                              // Route name
        "{controller}/{action}/{id}",                           // URL
        new { controller = "Home", action = "Index", id = "" }, // Defaults
        new[]{"Your.NameSpace"}                       // Namespaces
      );
    }
    

    【讨论】:

      猜你喜欢
      • 2021-06-04
      • 2011-07-08
      • 2014-05-19
      • 2020-11-14
      • 2023-02-11
      • 2014-07-28
      • 1970-01-01
      • 2014-05-11
      • 2016-03-12
      相关资源
      最近更新 更多