【问题标题】:Routing doesn't find controller with the same name as area路由找不到与区域同名的控制器
【发布时间】:2016-04-25 19:57:01
【问题描述】:

我关注了ASP:NET MVC 4 中有关区域的文章(如何避免名称冲突部分)。我正在使用 MVC 5,但我想版本 4 中的所有功能都可用并且应该在版本 5 中工作。

我的目录结构:

文件 EpicAreaRegistration.cs 内容:

namespace App1.Web.UI.Areas.Epic
{
  public class EpicAreaRegistration : AreaRegistration
  {
    public override string AreaName
    {
      get{ return "Epic"; }
    }

    public override void RegisterArea(AreaRegistrationContext context)
    {
      context.MapRouteLocalized(
         name: "Epic_default",
         url: "Epic/{controller}/{action}/{id}",
         defaults: new { controller = "Pm", action = "Index", id = UrlParameter.Optional },
         namespaces: new[] { "App1.Web.UI.Areas.Epic.Controllers" }
      );
    }
 }

}

我项目的 App_Start -> RouteConfig.cs 文件内容:UPDATE 更正了命名空间

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

      routes.MapRoute(
          name: "Default",
          url: "{controller}/{action}/{id}",
          defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional },
          namespaces: new[] { "App1.Web.UI.Controllers" } // according to article namespace must be added here, so ASP.NET router distinguishes between request: e
      );
    }
  }

最后我在项目的控制器目录中有 EpicController.cs 文件:

namespace App1.Web.UI.Controllers
{
  public class EpicController : Controller
  {
    public ActionResult Browse()
    {
      return View();
    }
  }

}

当我导航到:http://localhost:7300/Epic/Pm 时,它可以工作(找到它),但 http://localhost:7300/Epic/Browse 不起作用(404 - 未找到)。我错过了什么?

我的假设是请求通过某种路由表。如果在 Areas 中没有找到 Epic/Browse,它应该移动到项目的根 Controller 文件夹。这与 Views 的类比相同(文件夹,如果不在文件夹中,请在 Shared 中查找,...)

另外我在 Application_Start 中注册了所有区域

public class Global : HttpApplication
{
  void Application_Start(object sender, EventArgs e)
  {
    AreaRegistration.RegisterAllAreas();
    GlobalConfiguration.Configure(WebApiConfig.Register);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    ....

【问题讨论】:

    标签: c# asp.net asp.net-mvc-5


    【解决方案1】:

    确保您的 Area 控制器使用正确的命名空间。

    EpicController 的命名空间当前是:

    namespace App1.Web.UI.Controllers
    

    改成:

    namespace App1.Web.UI.Areas.Epic.Controllers
    

    【讨论】:

    • Zaki,谢谢你,这是我发布命名空​​间时的拼写错误(我隐藏了实际的应用程序名称,因此将其命名为 App1,但它仍然不起作用)。 +1 表示注意。
    【解决方案2】:

    您的控制器也是 Epic。所以你的 URL 看起来像

    http://localhost:7300/Epic/Epic/Browse

    【讨论】:

    • 区域的访问方式与项目根目录中的控制器相同,但带有前缀“区域名称”。如果您编写自定义路线图/规则,Epic/Epic 将起作用。
    • 他的区域也是在路由中定义的。这就是为什么我建议他以这种方式访问​​该网站。这是他唯一的路线,所以史诗/控制器名称(也是史诗)是他击中它的方式。
    【解决方案3】:

    这可能有助于您访问,

    http://localhost:7300/Areas/Epic/Epic/Browse
    

    因为它包含在子文件夹中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多