asp.net-mvcasp.net-mvc-2asp.net-mvc-routing

Why is the wrong controller being called when I start my ASP.NET MVC2 application?


I have a controller called MetricsController with a single action method:

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

I want to route calls to this controller like this:

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

I've mapped an additional route in my Global.asax.cs like this:

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 }
);

I just added this to the default template project that Visual Studio 2010 creates.

When I run the application, instead of defaulting to the HomeController, it starts in the MetricsController instead.

Why is this happening? There's nothing in the url when I start the application that matches the url pattern specified in the Metrics route.

This is all being tried in Visual Studio 2010 using the built-in web server.


Solution

  • Because it matches first root, of course.

    Thing is - when You provide default values - they become optional. If every one of routedata values are optional and route is first - it's guaranteed that it will hit first.

    Something like this should work:

    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 }
    );