Reputation:
I try to implement localization in Blazor application but I encounter some issues when try to get the resource value by key in the view.
How I can achieve this?
Here is my code so far:
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddLocalization(options => { options.ResourcesPath = "Resources"; });
services.Configure<RequestLocalizationOptions>(
options =>
{
List<CultureInfo> supportedCultures =
new List<CultureInfo>
{
new CultureInfo("bg-BG"),
new CultureInfo("en-US")
};
options.DefaultRequestCulture = new RequestCulture("bg-BG");
// Formatting numbers, dates, etc.
options.SupportedCultures = supportedCultures;
// UI string
options.SupportedUICultures = supportedCultures;
});
services.AddRazorPages();
services.AddServerSideBlazor().AddCircuitOptions(options => { options.DetailedErrors = true; });
services.AddApplicationRepositoryServices();
services.AddSingleton<WeatherForecastService>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRequestLocalization( app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>().Value);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAuthentication();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
Login.razor
@page "/login"
@using Microsoft.Extensions.Localization
@inject IStringLocalizer<Login> Localizer
<button type="submit" class="btn btn-primary w-100">@Localizer["LoginButtonText"]</button>
Page location
Project
-- Pages
---- Account
------ Login.razor
Resource files location
Project
-- Resources
---- Pages
------ Account
-------- Login.bg-BG.resx
Upvotes: 5
Views: 8858
Reputation: 1068
This works for me:
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
...
services.AddLocalization(options => { options.ResourcesPath = "Resources"; });
...
}
Index.razor
@page "/"
@using System.Globalization
<h1>Localization test</h1>
Localized field: @(localizer["Field1"])
@code {
[Inject] public Microsoft.Extensions.Localization.IStringLocalizer<Index> localizer { get; set; }
}
My resx
files are stored like this:
Resources\Pages\Index.resx
Resources\Pages\Index.cs.resx
...
Then, depending on the UICulture, the correct localized string is returned when calling localizer["Field1"]
.
In the code, I change the UICulture this way:
CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo("cs-CZ");
Upvotes: 13