Pergunta

If I have the following MapRoute:

routes.MapRoute(
    "Default",                                              // Route name
    "{controller}/{action}/{id}",                           // URL with parameters
        new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
);

I can have an url like:

blabla.com/Home/Index/123

But what kind of MapRoute do I need to create to be able to do this:

blabla.com/Home/123 or blabla.com/Home/DEADBEEF?

I imagine it involves something along the lines of "{controller}/{id}/{action}"

Action and id are reversed, and maybe there should be a default action. But how will the MapRoute know which controller should be treated like this?

Foi útil?

Solução

You probably need something along these lines.

  routes.MapRoute(
      name: "DefaultRoute",
      url: "Home/{action}",
      defaults: new { controller = "Home", action = "Index" },
      constraints: new { action = "[A-Za-z]*" }
  );

or without an action

  routes.MapRoute(
      name: "DefaultRoute",
      url: "Home/{id}",
      defaults: new { controller = "Home", action = "Index", id = "" },
      constraints: new { id = "[A-Za-z]*" }
  );

You will need to make sure that the route name is different than any other routes you have setup and pay attention to the ordering of the routes as other routes that are similar can override each other. In this case make sure you would probably want this before the default route but be aware that it will override it.

As for the not having controller or even the action you can set defaults and do not need them within the route.

As for constraints you can simply add the constraints parameter to the route to set a regular expression for a certain attribute as shown above.

EDIT: Here are some useful links for more info on routing if you need it.

Outras dicas

You can add a route like this:

routes.MapRoute(
    "CustomRoute",
    "Home/{id}",
    new { controller = "Home", action = "Index", id = "" });

Make sure you place it above the default route. However this route will block all the other actions in HomeController. Since we don't have a constraint on id parameter, the framework can't possibly know if you are referring to an action or an id in your URL. Since this route comes first, it will map it to id parameter.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top