Introduction
Blazor is a framework built by Microsoft for creating interactive client-side web UI with .NET codebase. We can write both client-side and server-side code in C#.NET. There are two hosting models available for Blazor: Blazor Server and Blazor WebAssembly. Blazor WebAssembly was released in May 2020, as per the Microsoft roadmap.
In this article, I will show how to use SQLite localization in a Blazor server-side application. We will have two cultures ("en" and "ru").
Create a Blazor server application using Visual Studio for Mac
Currently, Visual Studio for Mac 8.8 is available with the Blazor server template. Since we are creating a WebApp, I am using a Visual Studio extension to create it. This extension will provide the template for Razor.
Choose a template for your project: Blazor Server App, Next > Authentication: No Authentication, Next > ProjectName: (For example` BlazorSqlite), then create a solution.
Modify appsettings.json
In our project, we have an appsettings.json file. We need to open and modify it.
Add a Localization section for the SQLite file path. We will use it for getting translations for our keys.
Manage NuGet packages
There are many types of localization, but in this article, we will use SQLite localization. For that, we need to add "Localization.SqlLocalizer" from NuGet packages. We also need "Microsoft.EntityFrameworkCore.Sqlite '' for working with SQLite files.
Add the following packages to your project:
- Localization.SqlLocalizer
- Microsoft.EntityFrameworkCore.Sqlite
Modify Startup.cs
First of all, we need to get an SQLite connection string for our appsettings, and then add services and supported cultures.
Add the following code to your Startup > ConfigureServices:
- public void ConfigureServices(IServiceCollection services) {
- services.AddRazorPages();
- string sqlConnectionString = Configuration.GetSection("Localization").GetValue < string > ("ConnectionString");
- services.AddServerSideBlazor();
- services.AddDbContext < LocalizationModelContext > (options => options.UseSqlite(sqlConnectionString, b => b.MigrationsAssembly("BlazorSqlite")), ServiceLifetime.Singleton, ServiceLifetime.Singleton);
- var useTypeFullNames = true;
- var useOnlyPropertyNames = false;
- var returnOnlyKeyIfNotFound = true;
- var CreateNewRecordWhenLocalisedStringDoesNotExist = true;
- services.AddSqlLocalization(options => options.UseSettings(useTypeFullNames, useOnlyPropertyNames, returnOnlyKeyIfNotFound, CreateNewRecordWhenLocalisedStringDoesNotExist));
- services.AddMvc().AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);
- IList < CultureInfo > supportedCultures = new List < CultureInfo > ();
- CultureInfo defCulture = new CultureInfo("en");
- supportedCultures.Add(new CultureInfo("en"));
- supportedCultures.Add(new CultureInfo("ru"));
- services.AddSingleton < WeatherForecastService > ();
- services.Configure < RequestLocalizationOptions > (options => {
- options.DefaultRequestCulture = new RequestCulture(defCulture);
- options.SupportedCultures = supportedCultures;
- options.SupportedUICultures = supportedCultures;
- });
- }
** defCulture is your default culture.
** supportedCultures is yout project supported cultures (Ex` en/ru)
Add the following code to your Startup > Configure
After adding services, we need to add supported request cultures.
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
- IList < CultureInfo > supportedCultures = new List < CultureInfo > ();
- CultureInfo defCulture = new CultureInfo("en");
- supportedCultures.Add(new CultureInfo("en"));
- supportedCultures.Add(new CultureInfo("ru"));
- RequestLocalizationOptions localizationOptions = new RequestLocalizationOptions {
- DefaultRequestCulture = new RequestCulture(defCulture),
- SupportedCultures = supportedCultures,
- SupportedUICultures = supportedCultures
- };
- RouteDataRequestCultureProvider requestProvider = new RouteDataRequestCultureProvider();
- localizationOptions.RequestCultureProviders.Insert(0, requestProvider);
- CultureInfo.DefaultThreadCurrentCulture = defCulture;
- CultureInfo.DefaultThreadCurrentUICulture = defCulture;
- if (env.IsDevelopment()) {
- app.UseDeveloperExceptionPage();
- } else {
- app.UseExceptionHandler("/Error");
-
- app.UseHsts();
- }
- app.UseRequestLocalization(localizationOptions);
- app.UseHttpsRedirection();
- app.UseStaticFiles();
- app.UseRouting();
- app.UseEndpoints(endpoints => {
- endpoints.MapControllers();
- endpoints.MapBlazorHub();
- endpoints.MapFallbackToPage("/_Host");
- });
- }
** defCulture is your default culture.
** supportedCultures is your project supported cultures (Ex` en/ru)
Create CultureController
I'm using the SetCulture action, in order to change our project culture. It accepts two parameters. The first is culture, which we will change and the second is redirecUri, which we will use to redirect
Create a Controllers folder, then add 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);
- }
- }
Modify _Imports.razor
Append the following using, which will help to use IStringLocalizer in our razor pages.
- @using Microsoft.Extensions.Localization
Modify Index.razor in Pages
For using localization in razor pages, we need to do the following steps:
- Inject IStringLocalizer in the top as "Localizer"
- Use @Localizer["Hello, world"] so as to achieve getting translated value
- At the bottom, we need to write a function, which will help us to change the culture.
- Call "ChangeCulture" function in select.
- @page "/"
-
- @inject NavigationManager NavigationManager
- @inject IStringLocalizer<BlazorSqlite.Controllers.CultureController> Localizer
-
- <h1>@Localizer["Hello, world"]!</h1>
-
- @Localizer["Welcome to your new app"].
-
- <SurveyPrompt Title="How is Blazor working for you?" />
-
- <h3>Select your language</h3>
-
- <select @onchange="ChangeCulture">
- <option>Select culture</option>
- <option value="en">English</option>
- <option value="ru">Russian</option>
- </select>
-
-
- @code {
- private void ChangeCulture(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);
- }
- }
Now we can test our Blazor SQLite localization
- Run the project (ensure your SQLite path is correct)
- Change select value
Select English:
Select Russian:
SQLite File Example
Here is my SQLite file view:
Conclusion
In this post, I have explained how to set localization in the Blazor server app. I used Visual Studio Mac. In this example, I used a template project of the Blazor server app. I have used two cultures, English and Russian. Please feel free to send your feedback.
Thanks!