Live Chat Icon For mobile
Live Chat Icon

How do I change languages in a Blazor server-side application?

Platform: Blazor| Category: General

Languages are changed by using localization in the Blazor server-side application. In the following example, the languages are changed from English to French and vice versa by clicking a button. 

[Program.cs] 

builder.Services.AddLocalization(); 

builder.Services.AddLocalization(options => options.ResourcesPath = "Resources"); 
… 

var localizeOptions = new RequestLocalizationOptions() 

                .SetDefaultCulture("en-US") 

                .AddSupportedCultures("en-US", "fr-FR") 

                .AddSupportedUICultures("en-US", "fr-FR"); 

app.UseRequestLocalization(localizeOptions); 

app.MapControllers(); 
… 

[Culture.cs]

. . .
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;
namespace BlazorAppLocale
{
    [Route("/[controller]")]
    [ApiController]
    public class Culture : ControllerBase
    {
        public ActionResult SetCulture()
        {
            IRequestCultureFeature culture = HttpContext.Features.Get<IRequestCultureFeature>();
            Response.Cookies.Append(
                CookieRequestCultureProvider.DefaultCookieName,
                CookieRequestCultureProvider.MakeCookieValue(
                    new RequestCulture(new string[] { "en-US", "fr-FR" }
                    .Where(option => option != culture.RequestCulture.Culture.Name)
                    .FirstOrDefault())));

            return Redirect("/");
        }
    }
}

Add the culture resource files in the Resources/Pages folder.

[Index.razor]

@page "/"
@inject Microsoft.Extensions.Localization.IStringLocalizer<Resource> locale

<h1>@locale["Hello World"]</h1>

@locale["Welcome to your new app."]

<SurveyPrompt Title="How is Blazor working for you?" />

Add the button for changing the language.

[MainLayout.razor]

@inject NavigationManager UriHelper

<div class="top-row px-4"> 
    <button class="btn btn-secondary" @onclick="OnSelected">Change Language</button>
</div>

@code {

    private void OnSelected()
    {
        UriHelper.NavigateTo("Culture", true);
    }
}

You can download the reference sample here.

Please refer to this link for more information.

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.