Skip to content

Instantly share code, notes, and snippets.

@perosb
Last active September 11, 2021 15:56
Show Gist options
  • Save perosb/bfa8f641e379a0a9ba492c9900488a58 to your computer and use it in GitHub Desktop.
Save perosb/bfa8f641e379a0a9ba492c9900488a58 to your computer and use it in GitHub Desktop.
Sitecore 10.1 with .NET Core rendering and custom cultures on Linux

Sitecore 10.1 and .NET Core Rendering Host with Custom Cultures on Linux

In traditional Sitecore you can always install custom cultures using .NET Framework (unless you're on PaaS ;).

If you're running .NET Core RenderingHost on a alpine linux based container, you're options are a bit more limited. One way would be to build additional cultures into alpine but it's quite a hassle. You need to build the custom .dat file first etc.

However, it turns out that you can actually create new CultureInfo("en-IS") without them being installed. There is however one culprit, these cultures are not included in the GetCultures method. This method is used internally by Sitecore to validate the that the route contains a valid culture for the localization to work.

Luckily you can replace the contraint added by Sitecore with a custom version that looks like

public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
{
    if (!values.ContainsKey(RenderingEngineConstants.SitecoreLocalization.RequestCulturePrefix))
    {
        return false;
    }

    var lang = values[RenderingEngineConstants.SitecoreLocalization.RequestCulturePrefix].ToString();
    CultureInfo culture = null;
    if (!string.IsNullOrEmpty(lang))
    {
        culture = CultureInfo.GetCultures(CultureTypes.AllCultures)
                                .SingleOrDefault(c => c.IetfLanguageTag.Equals(lang, StringComparison.InvariantCultureIgnoreCase));

        if (culture == null && Regex.IsMatch(lang, "^[a-z]{2,3}(?:-[a-z]{2,3}(?:-[a-z]{4})?)?$"))
        {
            try
            {
                culture = new CultureInfo(lang);
            }
            catch (Exception ex)
            {
            }
        }
    }

    return culture != null;
}

Next, in your Startup.cs replace Sitecore version with your class:

services.Configure<RouteOptions>(options =>
{
    if (options.ConstraintMap.ContainsKey(RenderingEngineConstants.SitecoreLocalization.RequestCulturePrefix))
    {
        options.ConstraintMap[RenderingEngineConstants.SitecoreLocalization.RequestCulturePrefix] = typeof(LanguageRouteConstraint);
    }
});

That's it.

Note

you still need to install the custom cultures on the CM/CD side as usual. if you're to run RendeingHost in Windows container, you could also just install the cultures as with CM/CD and they should be picked up by GetCultures() method.

Cross posted to medium blog

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment