Search code examples
c#asp.net-mvcroutesasp.net-mvc-5routedebugger

c# MVC custom Route not matching


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


Solution

  • 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).