0

I've defined a custom route before my default route in MVC5, but it is not being hit for some reason. It hits the default route.

My routes are defined as follows:

        routes.MapRoute(
            name: "PDF Viewer",
            url : "pdf/{id}",
            defaults : new { controller = "PdfViewer", action = "Index", id = UrlParameter.Optional },
            namespaces : new[] { "App.Web.Controllers" }
        );
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults : new { controller = "Calendar", action = "Index", id = UrlParameter.Optional },
            namespaces : new[] { "App.Web.Controllers" }
        );

When navigating to /pdf/1 it isn't being caught by the route. Route Debugger shows the following results:

Route Debugger Output

hofnarwillie
  • 3,563
  • 10
  • 49
  • 73
  • 2
    And when your try `/PdfViewer/Index/1`? – haim770 Jun 23 '14 at 14:57
  • Ok, good idea. When using that URL it still returns a server error, but when I debug I don't get any errors in my `HandleError` attribute or my `Global.asax Application_Error` event – hofnarwillie Jun 23 '14 at 15:08
  • Is it 404 (Not found) or 500 (Server error)? – haim770 Jun 23 '14 at 15:09
  • @haim770 Ha! Not sure what happened, probably a caching issue, but I cleared my browser cache and tried again and then it actually caught the error in Global.asax. Here's the error `"The current request for action 'Index' on controller type 'PdfViewerController' is ambiguous between the following action methods: App.Web.Controllers.PdfViewerController.Index() and App.Web.Controllers.PdfViewerController.Index(Int32)"`. I don't get it though, I'm passing in the `Int32` in the url. – hofnarwillie Jun 23 '14 at 15:13
  • What's the name of the parameter being passed to `Index(int32 ...)`? – haim770 Jun 23 '14 at 15:18
  • @haim770 `id` - however, it's now solved as per my comment on your answer below. Merged the two actions into one by changing the action signature to `Index(int? id)`. – hofnarwillie Jun 23 '14 at 15:20

1 Answers1

2

Remove the id = UrlParameters.Optional from the 'PDF Viewer' route defaults.

When the id is optional, the framework considers the request as ambiguous because it can match both Index() and Index(int id).

haim770
  • 48,394
  • 7
  • 105
  • 133
  • But I want the url `/pdf` to go to the `Index()` action or should I have only one action with optional `int?` id parameter – hofnarwillie Jun 23 '14 at 15:15