Oskar Zetterberg
May 2, 2024
  433
(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
Copy Optimizely SaaS CMS Settings to ENV Format Via Bookmarklet

Do you work with multiple Optimizely SaaS CMS instances? Use a bookmarklet to automatically copy them to your clipboard, ready to paste into your e...

Daniel Isaacs | Dec 22, 2024 | Syndicated blog

Increase timeout for long running SQL queries using SQL addon

Learn how to increase the timeout for long running SQL queries using the SQL addon.

Tomas Hensrud Gulla | Dec 20, 2024 | Syndicated blog

Overriding the help text for the Name property in Optimizely CMS

I recently received a question about how to override the Help text for the built-in Name property in Optimizely CMS, so I decided to document my...

Tomas Hensrud Gulla | Dec 20, 2024 | Syndicated blog

Resize Images on the Fly with Optimizely DXP's New CDN Feature

With the latest release, you can now resize images on demand using the Content Delivery Network (CDN). This means no more storing multiple versions...

Satata Satez | Dec 19, 2024