2

I'd like to have one route that gives the option of two urls but maps to one action. A good example would be for multilingual application. Lets take english and french for example.

This seems simple at first, technically you can do:

routes.MapRoute(
  "the hi route english" ,
  "welcome/sayhi/{id}" ,
  new { controller = "Welcome" , action = "SayHi" , id = UrlParameter.Optional }
);

routes.MapRoute(
  "the hi route french" ,
  "bienvenu/direallo/{id}" ,
  new { controller = "Welcome" , action = "SayHi" , id = UrlParameter.Optional }
);

But that means that you'll have to define two routes for every action. Or a little better solution, create a custom Route class that takes more params to handle bilingualism.

If I go option 1 or 2, It means I have to define every single routes of the WelcomeController because I cannot use {action} in my route.

Ideally, i'd like to be able to define at least action name via metadata and then grab it via reflection or something.

i.e.:

[ActionName( { "fr", "direallo" }, {"en", "sayhi"})]
public ActionResult SayHi(string id){
     //check current thread culture...
}

I am not quite sure where to starts, any ideas? Tips?

Thank you,

tereško
  • 58,060
  • 25
  • 98
  • 150
Pierluc SS
  • 3,138
  • 7
  • 31
  • 44

1 Answers1

1

You have several options starting points here, roughly they are (in order of implementation complexity):

  • A route per language (as you outlined above)
  • A regex route constraint e.g.

    routes.MapRoute(
        "the hi route",
        "{controllerName}/{actionName}/{id}",
        new { controller = "Welcome" , action = "SayHi" , id = UrlParameter.Optional },
        new { controllerName = @"welcome|bienvenu", actionName = @"sayhi|direallo" }
    );
    
  • You could create a base controller, which is inherited by a subclass per language and define a language specific action name for each base controller action method

  • You could create your own (or use the one provided in the answer to the comment by Justin Pihony) custom routing constraint
Community
  • 1
  • 1
HOCA
  • 1,073
  • 2
  • 9
  • 20
  • If these are the only options, I guess last one remains the most elegant solution, and I already got it working :) – Pierluc SS Feb 27 '12 at 13:19
  • this gets tricky when you're domain defines the language you're in and then you have to add links depending on languages. – Pierluc SS Feb 28 '12 at 19:27