How to add a culture URL segment for localization in Orchard Core - Orchard Nuggets

Zoltán Lehóczky's avatar
Localization, Orchard Nuggets, Orchard Core, ASP.NET Core, Content Picker Menu Item, Kast case study - This week in Orchard (02/05/2020)

So you're building a localized Orchard Core site and want all URLs to be in the form of /culture-name/rest/of/the/url, e.g. /hu-HU/my-page. (Figure out what "hu-HU" is! Hint: It's not an owl, neither a rock band from Mongolia!) What do you need to achieve this?

Well, we've already seen how to localize content items to achieve this, but that's just for content pages. There is one small piece missing though: How to get the same functionality for controller actions, i.e. coded pages? There is nothing built into Orchard Core for this, actually. And the reason is that all you need is available in ASP.NET Core MVC already.

First, you'll need to set up RouteDataRequestCultureProvider so the URL segment indicating the culture will be used to set the culture of the current request. Just add this to your module's or theme's Startup class (if you don't yet know how to build a module, check out our Training Demo!):

services.Configure(options =>
{
    options.AddInitialRequestCultureProvider(new RouteDataRequestCultureProvider());
});

So far so good. Next, you'll need the controller actions you want to be culture-aware to be routed in a way that the culture name is included in the URL:

public class CultureAwareController : Controller
{
    [Route("{culture}/culture-aware"]
    public ActionResult CultureAwareAction()
    {
        // Build the result here.
    }
}

So now you'll be able to reach this action from under /hu-HU/culture-aware for example.

There's one final part missing: Building URLs for these actions. This is quite simple too, you'd e.g. create a link for this action like following:

<a asp-action="CultureAwareAction" asp-controller="CultureAware" asp-area="CultureAwareModule" asp-all-route-data="routeParams">Click here</a>

That's it!

Of course, this can get more complex. You can make route configuration as well as URL generation easier by centralizing this culture parameter handling, which is useful if you have loads of such controllers and links.

Did you like this post? It's part of our Orchard Nuggets series where we answer common Orchard questions, be it about user-facing features or developer-level issues. Check out the other posts for more such bite-sized Orchard tips and let us know if you have another question!

No Comments

Add a Comment