【问题标题】:Why is the wrong controller being called when I start my ASP.NET MVC2 application?为什么在我启动 ASP.NET MVC2 应用程序时调用了错误的控制器?
【发布时间】:2010-10-06 20:55:39
【问题描述】:

我有一个名为 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,而是从MetricsController 开始。

为什么会这样?当我启动与Metrics 路由中指定的 url 模式匹配的应用程序时,url 中没有任何内容。

这一切都在 Visual Studio 2010 中使用内置的 Web 服务器进行了尝试。

【问题讨论】:

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


    【解决方案1】:

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

    事情是-当您提供默认值时-它们成为可选的。如果每一个 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】:

    从您的 Metrics 路由中删除默认值:

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

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

    【讨论】:

      【解决方案3】:

      简而言之:它使用Matrics 路由,因为它匹配Matrics 路由。

      In long:默认路由定义了所有路由组件的默认值,所有路由组件都是可选的。您的Metrics 路由所做的只是添加另一个带有默认值的可选路由参数......它与默认路由基本上没有什么不同,因为整个路由都包含可选参数。

      如果你想让它工作,你需要区分你的Metrics 路由和默认路由。

      例如

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

      HTH,
      查尔斯

      旁注:

      什么都没有 在我启动时的 url 与 url 匹配的应用程序 指标中指定的模式 路线。

      让我们换个角度来看——url中的什么与默认路由中指定的url模式匹配?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-20
        • 1970-01-01
        • 2019-11-29
        • 1970-01-01
        相关资源
        最近更新 更多