Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (143).NET Core  (23)Angular  (39)ASP.NET  (47)ASP.NET Core  (53)ASP.NET MVC  (83)Azure  (26)Blazor  (48)DocIO  (18)Essential JS 2  (64)Essential Studio  (159)Flutter  (53)JavaScript  (134)Microsoft  (96)PDF  (48)React  (29)Succinctly series  (118)Syncfusion  (400)TypeScript  (30)Uno Platform  (2)UWP  (4)Vue  (25)Webinar  (14)Windows Forms  (52)WPF  (92)Xamarin  (105)XlsIO  (20)Other CategoriesBarcode  (4)BI  (29)Bold BI  (3)Build conference  (6)Business intelligence  (53)Button  (4)C#  (100)Chart  (40)Cloud  (8)Company  (445)Dashboard  (4)Data Science  (3)Data Validation  (2)DataGrid  (31)Development  (233)Doc  (7)eBook  (89)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (14)Extensions  (7)File Manager  (3)Gantt  (6)Gauge  (4)Git  (3)Grid  (24)HTML  (8)Installer  (1)Knockout  (2)LINQPad  (1)Linux  (1)M-Commerce  (1)Metro Studio  (11)Mobile  (140)Mobile MVC  (9)OLAP server  (1)Orubase  (12)Partners  (20)PDF viewer  (15)Performance  (2)PHP  (1)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (5)Road Map  (9)Scheduler  (15)SfDataGrid  (7)Silverlight  (21)Sneak Peek  (12)Solution Services  (2)Spreadsheet  (2)SQL  (4)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (9)Tips and Tricks  (17)UI  (62)Uncategorized  (68)Unix  (2)User interface  (49)Visual State Manager  (1)Visual Studio  (12)Visual Studio Code  (7)Web  (98)What's new  (62)Windows 8  (19)Windows App  (1)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Share on twitter
Share on facebook
Share on linkedin
Easily Reach a Global Audience with Localization Support in Your Blazor Apps

Easily Reach a Global Audience with Localization Support in Your Blazor Apps

“If you talk to a man in a language he understands, that goes to his head.

  If you talk to him in his language, that goes to his heart.”
–    Nelson Mandela

I hope your application, too, deserves to reach the hearts of its users! This is possible with localization support.

In Blazor, we have to follow the same approach defined for the ASP.NET Core framework. ASP.NET Core has provided the following three approaches to enable culture settings in an application:

  • QueryStringRequestCultureProvider
  • CookieRequestCultureProvider
  • AcceptLanguageHeaderRequestCultureProvider

Among these, the CookieRequestCultureProvider is the recommended approach for the Blazor framework at the moment. If localization is implemented through QueryStringRequestCultureProvider or the URL path, we will not be able to persist the cultural details while working with webSockets.

Let’s see how to implement localization in a Blazor web application through CookieRequestCultureProvider and switch among different cultures in this blog!

Set up the application culture through cookies

Follow these steps to set your desired culture in an application:

Step 1: Create a new _Host.cshtml.cs in the Pages folder.

Step 2: Add the following code example, which has to be read by the localization middleware.

Step 3: Set the current culture in that application.

#Pages/_Host.cshtml.cs

public class HostModel : PageModel
{
    public void OnGet()
    {
        HttpContext.Response.Cookies.Append(
            CookieRequestCultureProvider.DefaultCookieName,
            CookieRequestCultureProvider.MakeCookieValue(
                new RequestCulture(
                    CultureInfo.CurrentCulture,
                    CultureInfo.CurrentUICulture)));
    }
}

Now, let’s see what this code will do in the application.

The HostModel class acts as the starting point for page rendering along with the inherited PageModel class.

PageModel has some predefined handlers for the request sent to the page and the data used to render the page. The most common handlers defined in the PageModel are:

  • OnGet: To initialize the state needed for the page.
  • OnPost: To handle the submission.

So, by using the OnGet method, we can set the culture in an application to affect the culture state before rendering the page.

Step 4: Next, we should append the cookie for the culture with respect to the header using the CookieRequestCultureProvider.

The DefaultCookieName value is .AspNetCore.Culture, which represents the default name to track the user-defined culture details.  We can change the default value if required while creating the cookie for the culture.

The MakeCookieValue method will create the cookie for the culture, which requires two inputs, the cookie name and culture details.

Now, I am changing the default cookie value and culture to “fr” (French) as explained in the following code example.

#Pages/_Host.cshtml.cs
       
        public void OnGet()
        {

            HttpContext.Response.Cookies.Append(
                "LocalAppCulture",
                CookieRequestCultureProvider.MakeCookieValue(
                    new RequestCulture("fr")));       

        }

Step 5: Add the following code example in the index.razor page to check the culture change in the application.

#index.razor

Current culture is
<b>
    @CultureInfo.CurrentCulture.Name
</b>

You will get the output as shown in the following screenshot. You can see that the culture has been changed to French.Output

Note:You can cross-check the cookie name in the application tab of the browser console window.

Browser console window showing the Cookie name in the application tab

Switch among different cultures in an application

Follow these steps to switch among different cultures in a multi-lingual application.

Configure the cultures in an application

Step 1: In the startup.cs page, make the following changes in the code snippet of the application.

#startup.cs

public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddServerSideBlazor();
            services.AddSingleton<WeatherForecastService>();

            #region Localization
            services.Configure<RequestLocalizationOptions>(options =>
            {
                // Define the list of cultures which support your app
                var supportedCultures = new List<CultureInfo>()
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("fr-FR")
                };

                // Set the default culture
                options.DefaultRequestCulture = new RequestCulture("en-US");

                options.SupportedCultures = supportedCultures;
                options.SupportedUICultures = supportedCultures;
            });
            #endregion
        }

In this code example, we have added a list of cultures that we are going to experiment with in this application and we have also set the default culture to en-US.

SupportedCultures is defined for formatting the date, time, numbers, and so on.

SupportedUICultures is defined for the UI string that we have localized.

Step 2: Next, we need to add controllers in the endpoint of the application, as shown in the following code example. We are using the controllers to set the cookie and redirect the page in secure mode. Please remember, we should do the same localization cultures changes in the application configuration, too.

#startup.cs

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            -----
            -----
                app.UseRequestLocalization(app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>().Value);
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapBlazorHub();
                endpoints.MapFallbackToPage("/_Host");
            });
        }

Add Controller to set cookie

Follow these steps to add a controller to set a cookie in an application.

Step 1: Use the SetCulture method to set the culture of the application on each drop-down value change.

Step 2: Use the culture name and URL parameters to redirect after setting the culture, as done in the following code example.

#CultureController.cs

[Route("[controller]/[action]")]
    public class CultureController : Controller
    {
        public IActionResult SetCulture(string culture, string redirectUri)
        {
            if (culture != null)
            {
                HttpContext.Response.Cookies.Append(
                    CookieRequestCultureProvider.DefaultCookieName,
                    CookieRequestCultureProvider.MakeCookieValue(
                        new RequestCulture(culture)));
            }

            return LocalRedirect(redirectUri);
        }
    }

Note:
1.  Add the Controllers folder and then add the CultureController.cs file.
2.  Set the cookie using cookieRequestCultureProvider as discussed earlier in this blog.

Adding drop-down to switch cultures

Follow these steps to add a drop-down list box to switch among cultures in your application:

Step 1: In the index razor page, you have to add a drop-down to switch cultures on value changes.

Step 2: Redirect the cultureController, setCulture action result to set the cookie with culture name and current page URL like in the following code example.

#index.razor

@page "/"
@using System.Globalization

@inject NavigationManager NavigationManager

<h3>Select your language</h3>

<select @onchange="OnSelected">
    <option>Select...</option>
    <option value="en-US">English</option>
    <option value="fr-FR">Français</option>
</select>

Current Culture is <b> @CultureInfo.CurrentCulture.Name</b>

@code {
    private void OnSelected(ChangeEventArgs e)
    {
        var culture = (string)e.Value;
        var uri = new Uri(NavigationManager.Uri)
            .GetComponents(UriComponents.PathAndQuery, UriFormat.Unescaped);
        var query = $"?culture={Uri.EscapeDataString(culture)}&" +
            $"redirectUri={Uri.EscapeDataString(uri)}";

        NavigationManager.NavigateTo("/Culture/SetCulture" + query, forceLoad: true);
    }
}

Run the application

Now, run the application. Use the drop-down list box in the page to set the culture in your application as you like.
Localization Home Page

GitHub samples

You can download the sample project to update the culture of the application here.

Conclusion

In this blog, we learned how to enable localization support and switch between different cultures in your Blazor web application. Please refer to this documentation page to fully enjoy the features of the localization support.

Try our 65+ Blazor UI components by downloading the free 30-day trial or NuGet package, and feel free to have a look at our GitHub and online examples and to explore other available features.

If you have any questions about our products, please let us know in the comments below. You can also contact us through our support forumDirect-Trac, or feedback portal. We are always happy to assist you!

Tags:

Share this post:

Share on twitter
Share on facebook
Share on linkedin

Leave a comment

Popular Now

Be the first to get updates

Subscribe RSS feed
Scroll To Top