Showing posts with label routing. Show all posts
Showing posts with label routing. Show all posts

Oct 16, 2015

ASP.NET MVC routing ordering

Always place more specific route before less specific in your routes definitions ....
And I always forget it.
More specific route includes your parameters and so :
        
    routes.MapRoute("ReportsWithoutMISCode",
              "Reports/{Action}/{programObjectiveId}/{userName}",
              new { controller = "Reports", action = "Index" },
              new { programObjectiveId = @"\d+" },
              new[] { "Web.Controllers.Reports" });
     routes.MapRoute("ReportsWithMISCode",
              "Reports/{Action}/{programObjectiveId}/{userName}/{MISCode}",
              new { controller = "Reports", action = "Index" },
              new { programObjectiveId = @"\d+" },
              new[] { "Web.Controllers.Reports" });

; should be switched since second route ReportsWithMISCode is more specific, means having more parameters.

So it should be:

     routes.MapRoute("ReportsWithMISCode",
              "Reports/{Action}/{programObjectiveId}/{userName}/{MISCode}",
              new { controller = "Reports", action = "Index" },
              new { programObjectiveId = @"\d+" },
              new[] { "Web.Controllers.Reports" });
      routes.MapRoute("ReportsWithoutMISCode",
              "Reports/{Action}/{programObjectiveId}/{userName}",
              new { controller = "Reports", action = "Index" },
              new { programObjectiveId = @"\d+" },
              new[] { "Web.Controllers.Reports" });

It is interesting to note that in first case route works in awkward way. It gets matched but third parameter MISCode is appended as query param with question mark like this:

...ReportXXX/101/pt2?MISCode=MyMISCode

After switching to second solution we get friendly url.