【问题标题】:How to choose route in MVC3如何在 MVC3 中选择路由
【发布时间】:2012-01-09 07:02:27
【问题描述】:

我有 global.ascx 和三个路由

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



        routes.MapRoute(
           "TestRoute",
           "{id}",
           new { controller = "Product", action = "Index3", id = UrlParameter.Optional },
           new { id = @"\d+" } //one or more digits only, no alphabetical characters
       );

        routes.MapRoute(
           "TestCatalogRoute",
           "{id}",
           new { controller = "Home", action = "Index", id = UrlParameter.Optional }
       );

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "RsvpForm", id = UrlParameter.Optional } // Parameter defaults
            //new { controller = "Product", action = "Index2", id = UrlParameter.Optional } // Parameter defaults
        );


    }

当我输入网址时:

http://mydomain.com/

它使用“TestCatalogRoute”路由,但我想要“默认”路由 T.T

如何:

  • 带有网址:http://mydomain.com 它使用“默认”路由
  • 带有 url:http://mydomain.com/1 它使用“TestRoute”路由(已经完成!)
  • 带有 url:http://mydomain.com/abc 它使用“TestCatalogRoute”路由

【问题讨论】:

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


    【解决方案1】:

    然后删除id = UrlParameter.OptionalTestCatalogRoute

    【讨论】:

      【解决方案2】:

      更改路线的顺序。路由处理程序将验证每条路由,第一个匹配的将被选中。所以如果你把第二个放在最后,你应该没问题吧?

      【讨论】:

      • 这很好,但我认为“默认”路线呼喊终于找到了 :)
      • 你是对的,zerkms 是最好的答案。如果没有 id 参数,您的第二条路线将毫无用处,因此它不应该是可选的。
      【解决方案3】:

      我可以推荐使用 Routing Debugger 来调试你的易于使用的路由。

      http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-01-31
        • 1970-01-01
        • 1970-01-01
        • 2016-08-23
        • 2012-05-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多