【问题标题】:Why does my own controller result in a 404 error?为什么我自己的控制器会导致 404 错误?
【发布时间】:2013-10-19 09:06:20
【问题描述】:

我正在使用默认预设项目在其上构建我自己的应用程序。
我添加了我自己的控制器MyController 和一个新的视图目录Myindex.cshtml

这是控制器代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebProject1.Controllers
{
    public class MyController: Controller
    {
        //
        // GET: /My/

        public ActionResult Index()
        {
            return View();
        }

    }
}

这是我的RouteConfig.cs

// ...
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 = "My", action = "Index", id = UrlParameter.Optional }
        );
    }
}
// ...

但是,当我开始调试并导航到 /My/ 时,会显示 404 错误,并显示一条类似于 The resource or one of its dependencies cannot be found. 的消息。

如何让我的控制器工作?

【问题讨论】:

  • 请同时发布您的路线代码。路由中提到的默认控制器是什么?
  • 你有索引视图吗?
  • @HBhatia 是的,我创建了/Views/My/Index.cshtml
  • 路线看起来也正确。您可以发布浏览器正在搜索您的视图的位置吗?或者您是否通过保留断点来检查操作索引是否被命中。如果在浏览器中输入 /my/index 是否有效?
  • @ckv 嗯,不,控制器中的Index() 方法没有被命中。即使我手动输入完整的 URL。

标签: asp.net-mvc asp.net-mvc-4 http-status-code-404


【解决方案1】:

这几乎可以肯定是某个地方的错字。我建议从头开始重新创建您的控制器和视图。

【讨论】:

    【解决方案2】:

    除非您配置了任何区域,否则您应该能够在以下位置访问您的操作 localhost/My/Indexlocalhost/My,如果您有默认路由,并将操作作为索引。

    该错误还会为您提供 ASP.NET 正在搜索以定位您的视图的区域列表。

    【讨论】:

      【解决方案3】:

      创建自定义路由并将其放在默认路由之前。

      像这样:

          // ...
      public class RouteConfig
      {
          public static void RegisterRoutes(RouteCollection routes)
          {
           routes.MapRoute(
                 name: "me",
                 url: "me/{id}",
                 defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
             );
              routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
                  routes.MapRoute(
                  name: "Default",
                  url: "{controller}/{action}/{id}",
                  defaults: new { controller = "My", action = "Index", id = UrlParameter.Optional }
              );
          }
      }
      // ...
      

      希望这行得通...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-12-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多