I'm having trouble configuring localization in my asp.net 7.0 MVC project. Configuration:
.AddLocalization(opts => opts.ResourcesPath = "Resources")
then
CultureInfo[] supportedCultures = new[]
{
new CultureInfo("en-US"),
new CultureInfo("bg-BG")
};
mvcBuilder
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization();
mvcBuilder
.Services
.Configure<RequestLocalizationOptions>(options =>
{
options.DefaultRequestCulture = new RequestCulture(culture: "en-US", uiCulture: "en-US");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
});
This is called before
.AddRazorPages();
And at the end
app.UseRequestLocalization(app.Services.GetRequiredService<IOptions<RequestLocalizationOptions>>().Value);
I have installed Microsoft.Extensions.Localization nuget. I have two resource files in folder Resources
- Controllers.HomeController.bg-BG.resx
- Controllers.HomeController.en-US.resx
In both resources there is entry "title" with some values Injected IStringLocalizer into HomeController but everytime it returns only "title", used it like this:
this.stringLocalizer["title"].Value
After hours of trial and error I really can't seem to find what's the problem.
CodePudding user response:
You appear to be mixing up two different localization techniques. The .resx resource files is the classic .NET technique for localization while the IStringLocalizer
based approach has been added in .NET Core. Fortunately, it is still perfectly fine to utilize .resx resources .NET Core Views/Pages.
Add a using statement at the top of your view. Make sure that the namespace matches the actual C# namespace of your resource. The example below assumes that the default namespace of the project is WebApp
and the .resx files live inside a Resources
folder:
@using WebApp.Resources
Referencing a resource string inside your view is straight forward:
<h2>@Controllers_HomeController.title</h2>
NOTE: The underscore in Controllers_HomeController is caused your use of a .
in the resource filename, which would cause problems with the strongly typed generated class inside the corresponding Controllers_HomeController.Designer.cs
CodePudding user response:
The problem was something to do with the namespaces, changed the default namespace and it works now.