DEV Community

Chandu Sekhar
Chandu Sekhar

Posted on

Crafting Multilingual Experiences: Implementing Localization and Globalization in Blazor Server App

Introduction

In today's interconnected digital world, developing applications that communicate in your users' preferred language is essential, not optional. Let's explore how to set up a strong localization system in Blazor that can automatically identify and adapt to your users' language choices.

Understanding Localization and Globalization

Localization refers to the process of tailoring your application to suit various languages and cultural contexts. This includes translating text, formatting dates and numbers in line with local customs, and modifying layouts to fit different text lengths.

Globalization is about creating your application with the capability to support multiple cultures from the beginning. It entails adhering to international standards and best practices to make sure your application can be easily adapted for any market.

What We'll Build

  • A Blazor application that detects browser language settings
  • Custom middleware for handling culture settings
  • Resource-based localization implementation
  • A clean, maintainable approach to managing multilingual content

Prerequisites

  • .NET 8.0 or Greater
  • Basic understanding of Blazor
  • Visual Studio 2022 or VS Code

Getting Started with Blazor Localization

Blazor provides support for localization through the use of resource files (.resx). These files contain key-value pairs for different languages, allowing you to manage translations and other localized content effortlessly.

Setting Up the Project Structure

First, let's create our resource files structure:

YourProject/
├── Resources/
│   ├── Strings.resx          # Default/fallback culture
│   ├── Strings.es.resx       # Spanish
│   └── Strings.fr.resx       # French
├── Middleware/
│   └── RequestLocalizationMiddleware.cs
└── Program.cs
Enter fullscreen mode Exit fullscreen mode

Step 1: Creating the Localization Middleware

The middleware is responsible for detecting and setting the user's preferred language:

public class RequestLocalizationMiddleware
{
    private readonly RequestDelegate _next;

    public RequestLocalizationMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        var userLanguages = context.Request.Headers["Accept-Language"].ToString();
        if (!string.IsNullOrWhiteSpace(userLanguages))
        {
            var preferredLanguage = userLanguages.Split(',')[0];
            var culture = new CultureInfo(preferredLanguage);

            CultureInfo.DefaultThreadCurrentCulture = culture;
            CultureInfo.DefaultThreadCurrentUICulture = culture;
        }

        await _next(context);
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 2: Configuring Services

Add the necessary services in your Program.cs:

var builder = WebApplication.CreateBuilder(args);

// Add localization service
builder.Services.AddLocalization();

// ... other services

var app = builder.Build();

// Add the custom middleware
app.UseMiddleware<RequestLocalizationMiddleware>();

// ... rest of configuration
Enter fullscreen mode Exit fullscreen mode

Step 3: Using Localization in Blazor Components

Now you can use localization in your Blazor components:

Home.razor

@page "/"
@using Microsoft.Extensions.Localization
@inject IStringLocalizer<Strings> Localizer

<h1>@Localizer["Welcome"]</h1>
<p>@Localizer["HelloWorld"]</p>
Enter fullscreen mode Exit fullscreen mode

Step 4: Setting Up Resource Files

Create your resource files in the Resources folder:

  • Add Strings.resx to support default culture.
  • Add Strings.es.resx to support Spanish .
  • Add Strings.fr.resx to support French.

Now, for every resource (.resx) file set Custom Tool ** property value to **PublicResXFileCodeGenerator.

PublicResXFileCodeGenerator

  • It is a custom tool provided by Microsoft for working with .resx (resource) files in .NET projects.
  • It generates a .Designer.cs file from the .resx file.
  • This file contains a strongly-typed class with properties corresponding to the keys in the .resx file.

How It Works

  • When a user visits your application, the RequestLocalizationMiddleware checks their browser's Accept-Language header
  • The middleware sets the appropriate culture based on the user's preference
  • Blazor uses the IStringLocalizer to fetch strings from the matching resource file
  • If no matching culture is found, it falls back to the default resource file

Best Practices

Resource Organization

  • Keep resource keys consistent and meaningful
  • Use a hierarchical naming convention for complex applications
  • Consider separating resources by feature or module

Performance Considerations

  • Resource files are compiled into satellite assemblies
  • Cached by the framework for optimal performance
  • Consider using static analysis tools to find missing resources

Maintenance Tips

  • Document your resource keys
  • Use tools to manage translations
  • Implement a review process for translations

Advanced Features

You can extend this implementation with:

  • Culture switching
  • URL-based culture selection
  • Custom culture providers
  • Translation management systems

Conclusion

Implementing localization in Blazor is straightforward but powerful. This approach gives you a solid foundation for building multilingual applications that can reach users worldwide.

*Source Code *
Github

Top comments (0)