【问题标题】:The resource cannot be found. RouteConfig in mvc无法找到该资源。 mvc 中的路由配置
【发布时间】:2014-11-07 21:00:16
【问题描述】:

请看详情:

RouteConfig 类:

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 = "Home", action = "Index", id = UrlParameter.Optional}
                );
            routes.MapRoute(
                name: "Templates",
                url: "templates/{controller}/{template}",
                defaults: new { action = "Template" }
                );
        }
    }

团队控制器:

  public class TeamsController : Controller
    {
        public ActionResult Template(string template)
        {
            switch (template.ToLower())
            {
                case "list":
                    return PartialView(Url.Content("~/Views/Teams/List.cshtml"));
                case "add":
                    return PartialView(Url.Content("~/Views/Teams/Add.cshtml"));
                case "delete":
                    return PartialView(Url.Content("~/Views/Teams/Delete.cshtml"));
                case "edit":
                    return PartialView(Url.Content("~/Views/Teams/Edit.cshtml"));
                case "detail":
                    return PartialView(Url.Content("~/Views/Teams/Detail.cshtml"));
                default:
                    throw new Exception("template not known");
            }
        }
    }

网址请求:http://localhost:1533/templates/teams/add

错误:“/”应用程序中的服务器错误。

找不到资源。

为什么会出现这个错误?

【问题讨论】:

  • Default 路由移动到Templates 路由之后

标签: asp.net-mvc asp.net-mvc-routing


【解决方案1】:

尝试在RouteConfig.cs 文件中重新排序您的路线,如下所示:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapRoute(
            name: "Templates",                          //move custom routes above default routes
            url: "templates/{controller}/{template}",
            defaults: new { action = "Template" }
            );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new {controller = "Home", action = "Index", id = UrlParameter.Optional}
            );
    }
}

我在这里对您的问题提供一个小解释,以便您轻松理解,看看当我们运行我们的 mvc 应用程序时,会在 global.asax 文件中生成一个路由表,您可以在其中注册您的路由,以便按照您的路由默认路由将首先注册,默认路由将优先于您的自定义路由,因此始终建议将自定义路由置于默认路由之上,如我的回答所示。

一篇关于 MVC 路由中常见错误的好文章是 here 阅读此。

【讨论】:

    猜你喜欢
    • 2012-10-27
    • 2018-09-02
    • 1970-01-01
    • 2019-11-26
    • 2014-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多