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

Oskar Zetterberg
May 2, 2024
  403
(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
Optimizely SaaS CMS + Coveo Search Page

Short on time but need a listing feature with filters, pagination, and sorting? Create a fully functional Coveo-powered search page driven by data...

Damian Smutek | Nov 21, 2024 | Syndicated blog

Optimizely SaaS CMS DAM Picker (Interim)

Simplify your Optimizely SaaS CMS workflow with the Interim DAM Picker Chrome extension. Seamlessly integrate your DAM system, streamlining asset...

Andy Blyth | Nov 21, 2024 | Syndicated blog

Optimizely CMS Roadmap

Explore Optimizely CMS's latest roadmap, packed with developer-focused updates. From SaaS speed to Visual Builder enhancements, developer tooling...

Andy Blyth | Nov 21, 2024 | Syndicated blog

Set Default Culture in Optimizely CMS 12

Take control over culture-specific operations like date and time formatting.

Tomas Hensrud Gulla | Nov 15, 2024 | Syndicated blog

I'm running Optimizely CMS on .NET 9!

It works 🎉

Tomas Hensrud Gulla | Nov 12, 2024 | Syndicated blog

Recraft's image generation with AI-Assistant for Optimizely

Recraft V3 model is outperforming all other models in the image generation space and we are happy to share: Recraft's new model is now available fo...

Luc Gosso (MVP) | Nov 8, 2024 | Syndicated blog