使用每种语言的唯一资源文件使用IStringLocalizer本地化blazor [英] Localize blazor with IStringLocalizer using a unique resource file per language
问题描述
我正在尝试使用 IStringLocalizer
和基于Cookie的用户界面选择来本地化Blazor应用程序(.NET 5.0).遵循
I'm trying to localize my Blazor app (.NET 5.0) using IStringLocalizer
and user UI selection based on cookies. Following the documentation, it seems to work if I create a .resx
file for each page in my Resources/Pages
folder.
我想按以下方式将所有键值对归为一个文件:
I'd like to group all key-value pairs within a single file as follows :
MyApp
|-- Resources
| MyResources.resx <--- set to public modifiers to generate class!!!
| MyResources.es.resx
| MyResources.fr.resx
...
|-- Resources
| Index.razor
因此,在 Startup.cs
中,我注册了 Resources
文件夹:
So in Startup.cs
I register the Resources
folder:
services.AddControllers();
services.AddLocalization(options => options.ResourcesPath = "Resources");
我还在configure方法中添加了 MapControllers
,以及注册了支持的区域性.我还添加了控制器:
I also added MapControllers
in the configure method, as well as registering supported cultures. I also added the controller:
[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);
}
}
现在,在我的主要"index.razor"上页面我按如下方式注入 IStringLocalizer< MyResources>
:
Now, on my main "index.razor" page I inject the IStringLocalizer<MyResources>
as follows:
@page "/index"
@inject IStringLocalizer<Language> _localizer
<h2>@_localizer["hello_world"]</h2>
<h2>@DateTime.Now.ToShortDateString()</h2>
<h2>@DateTime.Now.ToLongDateString()</h2>
我确保所有 resx
文件实际上都包含"hello_world"文件,键,并添加一些语言选择器.
I make sure that all resx
files actually contain the "hello_world" key with some values and added a language selector.
当我运行该应用程序时,更改语言的确会更改显示的日期,但是,找不到 hello_world
键,因此该应用程序显示了该键.探索 _localizer
变量时,我发现容器为空- .resx
的键/值对均未真正加载.
When I run the app, changing the language does change the displayed dates, however, the hello_world
key is not found so the app displays the key instead. When exploring the _localizer
variable, I see that the container is empty - none of the key-value pairs of the .resx
are actually loaded.
是否可以使它正常工作?如果是这样,我在这里做什么错了?
Is it possible to get this to work? If so, what am I doing wrong here?
推荐答案
错误是由于在这里命名:
The mistake is because of naming here:
@inject IStringLocalizer<Language> _localizer
应该是
@inject IStringLocalizer<MyResources> _localizer
重要的是在项目的根目录添加一个空文件 MyResources.razor
.
And important is to add an empty file MyResources.razor
at the root of the project.
我犯的另一个错误是将 myApp.Resources
添加到 _Imports.razor
Another mistake I made is to add the myApp.Resources
to _Imports.razor
...
@using myApp.Resources <==== do NOT add this
这篇关于使用每种语言的唯一资源文件使用IStringLocalizer本地化blazor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!