Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 949
Kev Avatar asked Dec 17 '25 22:12

Kev


2 Answers

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 }
);
like image 69
Arnis Lapsa Avatar answered Dec 20 '25 01:12

Arnis Lapsa


Remove the defaults from your Metrics route:


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

With the default values MVC is able to map to the GetMetrics action in the Metric controller pretty much any URL that you pass to it.

like image 34
Hector Correa Avatar answered Dec 20 '25 02:12

Hector Correa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!