Course contentsShow
← C#
Lesson 1316 of 1,90812. Modern Frontend with Razor and BlazorFree lesson

Localization and Globalization

Implement multilingual UI support using resource files and locale-aware formatting.

In this lesson, you will learn how to make your Blazor and Razor applications globally accessible by decoupling UI strings from your source code and applying culture-specific formatting to data.

Globalization vs. Localization

While often used interchangeably, there is a distinct difference. Globalization is the process of designing your application to support multiple cultures (e.g., using CultureInfo for dates and currency), while Localization is the process of translating your application’s UI elements into specific languages.

Using Resource Files (.resx)

To localize your UI, move hardcoded strings into .resx files. In a Razor project, you typically create a Resources folder. For a file named SharedResource.resx, you would have a corresponding SharedResource.en.resx for English and SharedResource.fr.resx for French.

You then inject the IStringLocalizer<T> service into your components or views to fetch strings based on the user's current culture:

@inject IStringLocalizer<SharedResource> Localizer

<h1>@Localizer["WelcomeMessage"]</h1>

The engine automatically detects the browser's Accept-Language header and selects the correct resource file. If a key is missing in the specific culture file, it gracefully falls back to the default resource.

Locale-Aware Formatting

Globalization also requires that numbers, dates, and currency behave according to the user's region. In C#, the CultureInfo class handles these variations automatically. When you render data in your Razor markup, you should use standard format strings combined with the current thread's culture:

// Current culture automatically dictates the output
<p>Current Price: @price.ToString("C")</p>

If a user from the United States visits, they see "$10.00". A user from Germany visiting the same page will see "10,00 €".

To ensure your application respects these settings, configure your Program.cs by enabling request localization:

var supportedCultures = new[] { "en-US", "fr-FR" };
app.UseRequestLocalization(new RequestLocalizationOptions()
    .AddSupportedCultures(supportedCultures)
    .AddSupportedUICultures(supportedCultures));

By leveraging IStringLocalizer for text and CultureInfo for data formatting, you ensure your application feels native to users regardless of their location.

Key Takeaway: Use resource files to externalize UI strings and rely on CultureInfo to automatically handle regional variations in dates, currency, and number formats.