首页 > 解决方案 > 如果我在 RouteConfig 中更改它的顺序,为什么这条路线不起作用?

问题描述

当我访问这条路线http://localhost:60015/myroute时,如果路线的顺序如下所示,它将不起作用:

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(
           "myroute",
           "myroute/{name}",
           new { controller = "myroute", action = "search", name = "" }
         );

    }

如果我颠倒顺序,它会起作用。这意味着什么?这是怎么发生的?

标签: asp.netasp.net-mvc

解决方案


这是因为您添加到路由表的路由顺序很重要。您的新自定义路由应添加到现有默认路由之前。如果您颠倒了顺序,那么将始终调用默认路由而不是自定义路由。


推荐阅读