November Happy Hour will be moved to Thursday December 5th.

Oskar Zetterberg
May 2, 2024
  414
(1 votes)

Adding market segment for Customized Commerce 14

Since v.14 of commerce, the old solution for adding market segment to the url is not working anymore due to techinal changes of .NET Core. There is a post about adding market segment to Commerce 14 but that is about CMS and never got around with the commerce part. In that post Johan Björnfot added a comment suggesting using IContentUrlGeneratorEvents (thanks for the tip) and that is the approach I have used in my solution. No route mappings or overrides of internal components is needed.

In an initialization class add two methods and attach them to the url generator events :

public void Initialize(InitializationEngine context)
{
    var urlGeneratorEvents = context.Locate.Advanced.GetInstance<IContentUrlGeneratorEvents>();
    urlGeneratorEvents.GeneratedUrl += OnGeneratedUrl;

    var urlResolverEvents = context.Locate.Advanced.GetInstance<IContentUrlResolverEvents>();
    urlResolverEvents.ResolvingUrl += OnResolvingUrl;
}

private void OnGeneratedUrl(object sender, UrlGeneratorEventArgs e)
{
}

private void OnResolvingUrl(object sender, UrlResolverEventArgs e)
{
}

OnGeneratUrl, responsible for adding the market segment to the url.

private void OnGeneratedUrl(object sender, UrlGeneratorEventArgs e)
{
    // Validate if the url is a relative url and if it is a media file which we will not handle
    if (e.Context.Url.Path.StartsWith("/") && !IsMedia(e.Context.Url.Path))
    {
        var segments = e.Context.Url.Path.Split(new [] { '/' }, StringSplitOptions.RemoveEmptyEntries);

        // More validation, if the url does not contain any / or if the first segment have greater length then 2 then we consider it to be a non language
        if (segments.Length < 1 || segments[0].Length > 2)
        {
            return;
        }

        var currentUrlMarketSegment = segments.Length > 1 ? segments[1] : null;

        // Get the market, could be with ICurrentMarket or cookie value. Where ever the current market is stored or can be retrieved by current language
        var marketSegment = GetMarketSegment(e.Context.Language, currentUrlMarketSegment);
        
        if (!string.IsNullOrEmpty(marketSegment))
        {
            var langMarketArg = $"/{segments[0]}/{marketSegment}/";

            if (!e.Context.Url.Path.StartsWith(langMarketArg))
            {
                var languageArg = $"/{segments[0]}/";

                // Validate if market segment already exists in the current url. If so, add that to part to be replaced.
                // AvailableMarketSegments just returns all available segments as a string array
                if (currentUrlMarketSegment != null && currentUrlMarketSegment.Length == 2 && AvailableMarketSegments.Contains(currentUrlMarketSegment))
                {
                    languageArg += $"{currentUrlMarketSegment}/";
                }

                // Note, this value will be cached by Optimizley. That is why we need to check an existing market segment above.
                e.Context.Url.Path = e.Context.Url.Path.Replace(languageArg, langMarketArg);
            }
        }
    }
}

OnResolvingUrl, responsible for removing the market segment from the url so the "normal" url resolving can take place.

private void OnResolvingUrl(object sender, UrlResolverEventArgs e)
{
    // Skip if url is media
    if (IsMedia(e.Context.Url.Path))
    {
        return;
    }

    var segments = e.Context.Url.Path.Split(new [] { '/' }, StringSplitOptions.RemoveEmptyEntries);
    
    if (segments.Length >= 2)
    {
        // Validate if segments are valid language and valid market and replace incoming segments with language only to let Optimizley resolve it internally
        if (AvailableLanguageSegments.Contains(segments[0]) && AvailableMarketSegments.Contains(segments[1]))
        {
            var replaceArg = segments[0] + "/" + segments[1] + "/";
            e.Context.RemainingSegments = e.Context.RemainingSegments.ToString()
                .Replace(replaceArg, segments[0] + "/", StringComparison.OrdinalIgnoreCase).AsMemory();
            e.Context.Url = new Url(e.Context.Url.Uri.OriginalString.Replace(replaceArg, segments[0] + "/"));
        }
    }
}

Take note, as markets are contextual, using the UrlResolver it will resolve market from the current context. So if you are storing urls in some searchindex or something like that, make sure you handle the urls accordingly. We are for example storing urls without language- and market segment and are adding those in the correct context when requested.

The code can for sure be optimized and improved. Comment with suggestions.

Hope this will be to use for someone.

May 02, 2024

Comments

Please login to comment.
Latest blogs
CMS Core 12.22.0 delisted from Nuget feed

We have decided to delist version 12.22.0 of the CMS Core packages from our Nuget feed, following the discovery of a bug that affects rendering of...

Magnus Rahl | Dec 3, 2024

Force Login to Optimizely DXP Environments using an Authorization Filter

When working with sites deployed to the Optimizely DXP, you may want to restrict access to the site in a particular environment to only authenticat...

Chris Sharp | Dec 2, 2024 | Syndicated blog

Video Guides: Image Generation Features in Optimizely

The AI Assistant for Optimizely now integrates seamlessly with Recraft AI, providing advanced image generation capabilities directly within your...

Luc Gosso (MVP) | Dec 1, 2024 | Syndicated blog

DAM integration new major version, performance improvements and Library Picker folder selection

As you might already have seen we have decided to delist the EPiServer.CMS.WelcomeIntegration version 1.4.0 where we introduced Graph support....

Robert Svallin | Nov 29, 2024