Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Localizing/translating routes in ASP.NET MVC

Anyone knows a nice solution to localize routes in ASP.NET MVC? What I'd like to achieve is that these two urls point to the same action/resource:

  • http://example.org/Products/Categories (en)
  • http://example.org/Produkte/Kategorien (de)

Also there should be the possibility to generate the routes according to the current culture (or the default, if there are no translations available). Alternately, if I was able to specify just one culture so that only one of the two links above would work, that'd be also viable.

I tried a very nice approach by Maarten Balliauw, but his solution unfortunately doesn't work with Html.RenderAction(...).

Of course I could just add routes for all translations like

routes.MapRoute(
    "Products_Categories",
    "Produkte/Kategorien",
    new { controller = "Products", action = "Categories" }
);

but that would end up in an enormous amount of routes and it'd be very unflexible. Any better solution would be appreciated :-) The more flexible the better.

like image 653
davehauser Avatar asked Jun 03 '11 14:06

davehauser


3 Answers

You can try the awesome AttributeRouting project that I just found! You can get it through NuGet.

like image 52
Leniel Maccaferri Avatar answered Oct 27 '22 10:10

Leniel Maccaferri


This might be a viable way to manage all your routes - or some variation of it such as defining the routes in an XML file

http://www.iansuttle.com/blog/post/ASPNET-MVC-Store-Routes-in-the-Database.aspx

you'll still end up with a large number of routes but managing them would be a hell of a lot easier

like image 29
Beno Avatar answered Oct 27 '22 11:10

Beno


A simple solution for both attribute and conventional-based routing can be found at https://github.com/boudinov/mvc-5-routing-localization

You can get these working with /de prefix, as it is the preferred schema. You need to have 'Products' and 'Categories' translated to German in a resource file:

  • http://example.org/Products/Categories
  • http://example.org/de/Produkte/Kategorien

    [LocalizedRoute("~/Products/Categories", translateUrl: true]
    ActionResult Index(...)
    

Or working answer to the original question, without the language prefix, you can get like this:

  • http://example.org/Products/Categories
  • http://example.org/Produkte/Kategorien

    [LocalizedRoute("~/Products/Categories", translateUrl: false, explicitCulture: "en")]
    [LocalizedRoute("~/Produkte/Kategorien", translateUrl: false, explicitCulture: "de")]
    ActionResult Index(...)
    
like image 30
Plamen Boudinov Avatar answered Oct 27 '22 11:10

Plamen Boudinov