How do I configure ASP.NET MVC 3 routing so it doesn’t require the controller and action in the url?
I have this to display the details for item “abc123”, configured with the default routing-settings:
mysite.com/Home/Details/abc123
The value "abc123" is a unique value which the Home controller uses to look up the correct item in a database.
But I would prefer to have these ultra-short urls instead:
mysite.com/abc123
The site will also have very few additional controllers, such as “About” and “Contact”. I assume I would have to configure those specifically as well, so the default controller doesn’t start looking for details for an item with ID “About” or “Contact”. How do I do that?
UPDATE:
Here's what my routes ended up looking like:
routes.MapRoute("About", "About", New With {.controller = "About", .action = "Index"})
routes.MapRoute("ID", "{id}", New With {.controller = "Home", .action = "Details"})
routes.MapRoute("Default", "", New With {.controller = "Home", .action = "Index"})
:)
Try something like this:
routes.MapRoute("Site"
, "Site/{controller}/{action}"
, new { controller = "Home", action = "Index"});
routes.MapRoute("Id"
, "{id}"
, new { controller = "Home", action = "Details"});
The first route should ensure that you can have /Site/About and /Site/Contact mapped to AboutController and ContactController respectively. It is important that this gets mapped first.
The second route will make sure that /abc123 gets mapped to the details action with id "abc123"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With