Add routing in case of missing “action” in url ({controller}/{id}

Question!

How can I set up a {controller}/{id} routing in ASP.NET MVC 5. What I would like to achieve: if there are no {action} defined, call Index() with id.

I tried thism but didn't work:

// Keep default routing
routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

// Add own routing in case of missing "action"
routes.MapRoute(
    name: "Controller/Id",
    url: "{controller}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);


Answers

After reading ameer's comment it become clear that the routing is not that "intelligent" that I was hoping for, so if the URL pattern is matching one route, but no such controller/method found, it will not "fall through" to the next routing command, but will raise exception.

So I had tried what Simon suggested, added constraint to my custom routing, and reversed the order, and it works now. However, if I would like to have other mappings similar to attachments, I'd have to add them one by one.

Working code:

routes.MapRoute(
    name: "Attachments",
    url: "attachments/{id}",
    defaults: new { controller = "Attachments", action = "Index", id = UrlParameter.Optional }
);

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);


This video can help you solving your question :)
By: admin