Controllerless routing and action in the url

How to configure ASP.NET MVC 3 routing so that it does not require the controller and action in the URL?

I have this to display the details for the element "abc123" configured with the default routing settings:

mysite.com/Home/Details/abc123

The value "abc123" is a unique value that the Home controller uses to find the correct item in the database.

But I would prefer to use these ultra-short URLs:

mysite.com/abc123

There will also be very few additional controllers on the site, such as O and Contact. I assume that I will also have to configure them specially, so the controller does not by default look for details for an element with the identifier “O” or “Contact”. How to do it?

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"})

:)

+3
source share
3 answers

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 is displayed first.

In the second route, make sure that / abc 123 maps to the action of the part with the identifier "abc123"

+5
source

you can use this.

routes.MapRoute("abc123"
              , "Home/Details/{name}"
                , new { controller = "Home", action = "Detail", name = ""});

and your action is as follows:

public ActionResult Detail(string name)
{
  //...
}
+1
source

You can also do something like this:

routes.MapRoute("abc123", "abc123", new { controller = "Home", action = "Details"});

I am using MVC3 and it works for me.

0
source

All Articles