I am developing a blazor server app and now I want to use localization.
I create res1.en.resx
and res1.fr.resx
, but I can't create a designer class, it throw an exception, but no logs. I tried to create a normal resource file, I succedded.
So I think maybe ResXFileCodeGenerator doesn't support localization resource file? If I can't create the designer class, I can't user IStringLocalizer either, for no class can be passed in as generic arguments.
I had a test in my side with VS 2022 and .net 7 blazor server application. I followed this official document. Firstly, it mentioned that
IStringLocalizer and IStringLocalizer are supported in Blazor apps.
And it doesn't mention the ResXFileCodeGenerator
is necessary for IStringLocalizer
in blazor server. But I also test it. I had Resource folder and res1.resx res1.fr.resx res1.cn.resx
. When I add property ResXFileCodeGenerator
to Custom Tool
, VS will generate Designer file automatically. But it won't generate file when I add this property to other resx files.
Then I added builder.Services.AddLocalization();
and put below codes just behind app.UseRouting();
var supportedCultures = new[] { "fr", "en-US", "zh-CN" };
var localizationOptions = new RequestLocalizationOptions()
.SetDefaultCulture(supportedCultures[0])
.AddSupportedCultures(supportedCultures)
.AddSupportedUICultures(supportedCultures);
app.UseRequestLocalization(localizationOptions);
Then in my Index.razor component, I have codes below which displayed correctly for me. I change the language by modifying the language configuration in browser.
@using BlazorAppHotRelaod.Resources
@using Microsoft.Extensions.Localization
@using System.Globalization
@inject IStringLocalizer<res1> Loc
<p>
<b>CurrentCulture</b>: @CultureInfo.CurrentCulture
</p>
<p>
@Loc["Hello"]
</p>