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.

[Startup.cs]

public class Startup
    {
      . . .
      . . .
              public void ConfigureServices(IServiceCollection services)
        {
            . . .
            services.AddLocalization();
            services.AddLocalization(options => options.ResourcesPath = "Resources");
        }
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
          . . .
                     var localizeOptions = new RequestLocalizationOptions()
                .SetDefaultCulture("en-US")
                .AddSupportedCultures("en-US", "fr-FR")
                .AddSupportedUICultures("en-US", "fr-FR");

            app.UseRequestLocalization(localizeOptions);
                       .  .  .
                       .  .  .
                       app.UseEndpoints(endpoints =>
            {
                endpoints.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

Share on twitter
Share on facebook
Share on linkedin

Related FAQs

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

Please submit your question and answer.