代码之家  ›  专栏  ›  技术社区  ›  erlando

为什么在我启动ASP.NETMVC2应用程序?

  •  3
  • erlando  · 技术社区  · 15 年前

    我有一个叫 MetricsController 使用单一操作方法:

    public class MetricsController
    {
      public ActionResult GetMetrics(int id, string period)
      {
        return View("Metrics");
      }
    }
    

    我要将调用路由到此控制器,如下所示:

    http://mysite/metrics/getmetrics/123/24h

    Global.asax.cs 这样地:

    routes.MapRoute(
      "Metrics",
      "{controller}/{action}/{id}/{period}",
      new { controller = "Metrics", action = "GetMetrics", id = 0, period = "" }
    );
    
    routes.MapRoute(
      "Default", // Route name
      "{controller}/{action}/{id}", // URL with parameters
      new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
    

    我刚刚将此添加到Visual Studio 2010创建的默认模板项目中。

    HomeController ,开始于 度量控制器 相反。

    为什么会这样?当我启动与在 Metrics 路线。

    3 回复  |  直到 15 年前
        1
  •  1
  •   Arnis Lapsa    15 年前

    当然,因为它匹配第一个根。

    问题是-当您提供默认值时-它们变为可选的。如果routedata值中的每一个都是可选的,并且route是第一个,那么它保证会首先命中。

    routes.MapRoute(
      "Metrics",
      "Metrics/GetMetrics/{id}/{period}",
      //assuming id, period aren't supposed to be optional
      new { controller = "Metrics", action = "GetMetrics" }      
    );
    
    routes.MapRoute(
      "Default", // Route name
      "{controller}/{action}/{id}", // URL with parameters
      new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
    
        2
  •  1
  •   Hector Correa    15 年前

    从度量路由中移除默认值:

    
    routes.MapRoute(
      "Metrics",
      "{controller}/{action}/{id}/{period}",
      new { controller = @"Metrics", action = "GetMetrics"}
    );
    

    使用默认值,MVC可以映射到Metric控制器中的GetMetrics操作,几乎可以映射到您传递给它的任何URL。

        3
  •  1
  •   Arnis Lapsa    15 年前

    Matrics 因为它符合 矩阵 路线。

    In long:默认路由定义所有路由组件的默认值,所有路由组件都是可选的。你的一切 Metrics route正在添加另一个具有默认值的可选route参数。。。它基本上与默认路由没有区别,因为整个路由包含可选参数。

    韵律学 从默认路由路由。

    例如。

    routes.MapRoute(
      "Metrics",
      "metrics/{action}/{id}/{period}",
      new { controller = @"Metrics", action = "GetMetrics", id = 0, period = "" }
    );
    

    HTHs公司,

    旁注:

    什么都没有 与url匹配的应用程序 度量中指定的模式 路线。

    让我们从另一个角度来看这个问题-url中的哪些内容与默认路由中指定的url模式相匹配?