Blazor Tutorial: Using SEO-Friendly Culture Links

Last Update 10/11/2024 Blazor Server | VS 2022 | .NET 8 | TablerForNet

Welcome to this tutorial on using SEO-friendly culture links in Blazor applications. In this tutorial, you will learn how to change the culture of your Blazor application while ensuring that your page URLs are search engine-friendly. This will enable your application to be better indexed by search engines and provide an enhanced user experience for different cultural regions. Let's get started!

Getting Started with SEO-Friendly Culture Links in Blazor

The tutorial will cover the implementation of the following aspects:

  • Changing the Application Culture: Learn how to modify the culture setting within your Blazor application.
  • Structured URL Schema: Discover how to structure your URLs as www.ghostlyInc.com/en-US/siteName to represent different cultures.
  • Browser-Based Culture Change: Understand how users can dynamically alter the culture using their browser settings.
  • Error Handling for Culture Change: Implement robust error handling when users attempt to change to an unsupported or incorrect culture link.
  • SEO-Friendly and Culture-Specific URLs: Ensure your URLs are optimized for search engines and tailored to specific cultures.
  • Enhanced Search Engine Indexing: Elevate your search engine ranking and enhance user experience by adopting proper cultural localization practices.




Implementing SEO-Friendly Culture Links: The Code


Now, let's delve into the code implementation that enables SEO-friendly culture links in your Blazor application. Follow along as we walk you through each step of the process.



Now we need a Culture Controller. This controller ensures that when the culture changes, we are redirected to the new page.



We have now created a Culture Service and a Culture Controller. Modify with the following steps the file Progarm.cs

  • Add the culture service
  • Set the default culture to the first supported culture in the list.
  • Add the list of supported cultures for content localization.
  • Add the list of supported UI cultures for user interface localization.
  • Apply the configured localization options to the request pipeline.
  • Map incoming HTTP requests to their corresponding controller actions.




Modify with the following steps the file _host.cshtml

  • Inject the CultureService
  • Set the HTML lang attribute
  • Set a Culture cookie in the body tag



Modify with the following steps the file App.razor

  • Inject the CultureService
  • Inject the NavigationManager
  • Add the code section shown below in code

@inject NavigationManager Navigation
@inject CultureService cultureService

@code {

    /// <summary>
    /// This section handles redirection to a new culture when the user changes the culture in the browser link.
    /// If you don't wish to support this, you can delete this code.
    /// By default, it redirects to the current culture if no culture is specified in the link.
    /// </summary>
    /// <param name="firstRender">Indicates whether this is the initial rendering of the page</param>
    protected override void OnAfterRender(bool firstRender)
    {
        if (firstRender)
        {
            // Check if the link contains a specified culture
            var culture = cultureService.GetCultureFromLink(Navigation.Uri, Navigation.BaseUri);

            // If the culture string is null or empty, it's the page's first load. In this case, set the culture from the browser settings.
            if (string.IsNullOrEmpty(culture)) culture = CultureInfo.CurrentCulture.Name;

            // Check if the culture is supported by the application
            if (!cultureService.IsCultureSupported(culture))
            {
                // Try to set the language contained in the culture
                culture = cultureService.HandleUnsupportedCulture(culture);
            }

            var cultureInfo = new CultureInfo(culture);

            // If the current culture differs from the specified culture, set the new culture
            if (!CultureInfo.CurrentCulture.Name.Equals(culture))
            {
                cultureService.SetCulture(cultureInfo);
            }
        }
    }
}

Create a new component just for testing different cultures ChangeCulture.razor



@using System.Globalization
@inject CultureService cultureService

<button @onclick="() => SetCulture(Englisch)"> Englisch</button>
<button @onclick="() => SetCulture(Arabische)"> Arabische</button>
<button @onclick="() => SetCulture(France)"> France</button>
<button @onclick="() => SetCulture(Austria)"> Austria</button>
<button @onclick="() => SetCulture(Germany)"> Germany</button>

@code {
    private string Englisch = "en-US";
    private string Arabische = "ar-AE";
    private string France = "fr-FR";
    private string Austria = "de-AT";
    private string Germany = "de-DE";

    private void SetCulture(string culture)
    {
        cultureService.SetCulture(new CultureInfo(culture));
    }
}


Modify with the following steps the file MainLayout.razor

  • Inject the CultureService
  • Inject the NavigationManager
  • Add the before create component
  • Add below shown code section

@inject NavigationManager navi
@inject CultureService cultureService

<article class="content px-4">
    <ChangeCulture/>
    @Body
</article>

@code {
    // Here we redirect to culture link, for example, from www.example.com to www.example.com/de-DE/
    protected override void OnAfterRender(bool firstRender)
    {
        // Only perform this logic on the first render
        if (firstRender)
        {
            // Extract the relative path from the current URI by removing the base URI
            var currentUri = navi.Uri.Replace(navi.BaseUri, ");

            // Find the index of the first slash in the relative path
            int firstSlashIndex = currentUri.IndexOf('/');

            // Prepare the culture-specific URI
            string uri;
            if (firstSlashIndex >= 0)
            {
                // Extract the part of the relative path after the first slash
                string result = currentUri.Substring(firstSlashIndex + 1);

                // Construct the culture-specific URI
                uri = "/" + cultureService.Culture + "/" + result;
            }
            else
            {
                // If no slash was found in the relative path, navigate to the root path for the current culture
                uri = "/" + cultureService.Culture + "/";
            }

            // Navigate to the determined URI
            navi.NavigateTo(uri, false, false);
        }

        // Call the base OnAfterRender method to ensure proper functioning of the component
        base.OnAfterRender(firstRender);
    }
}



Now, with SEO-friendly culture links implemented across all pages in Blazor, you've established a consistent approach that applies to existing and future pages alike. As we move forward with this Blazor SEO tutorial, we'll apply the same set of steps to the following pages, ensuring a streamlined and uniform process.

  • Inject the CultureService
  • Create a Culture parameter
  • Set the culture parameter in the methode OnInitialized
  • Add the Culture Parameter to the page tag

The following code demonstrates the changes on the page fetchdata.razor



The final step is to integrate the culture service into the navigation bar. This ensures that we always navigate to the current culture.

Modify with the following steps the file NavMenu.razor

  • Inject the CultureService
  • Add the current culture to all links



SEO-friendly culture links in Blazor are important because they:

  • Improve Discoverability: Including culture in URLs helps search engines recognize language-specific content, leading to better search rankings.
  • Enhance User Experience: Users see familiar language tags in URLs, increasing trust and engagement.
  • Ensure Consistency: All pages maintain the same culture link structure, creating a seamless navigation experience.
  • Support Multilingual Content: Easily switch between languages while preserving the current page context.
  • Future-Proofing: Implementing this approach ensures new pages follow the same pattern, promoting scalability.
  • Global Reach: Attract a wider audience by catering to various language preferences and regions.

We're now done with the tutorial. Keep in mind that for any future pages, you'll need to follow the last two steps again. If you're adding links in your code, make sure to include the culture in the link to ensure proper functionality.