它打印Hello的原因是因为它cannot find与the class or view you want to localize匹配的本地化资源文件,当它找不到资源名称/键时,它会按原样打印文本(键)。
本地化有两种方法:
A) 如果您决定采用官方文档(using Localizer/IStringLocalizer) 中提到的方式,您需要执行以下操作:
- 创建一个 Resources 文件夹并将
.resx files 放入其中 使用正确的命名约定:
您需要命名您的 .resx files 以模仿您想要本地化的关联 view/class file 的路径。
例如:如果您有一个带有Index action 的HomeController,并且您有一个位于Views/Home/Index.cshtml 下的索引视图,那么您需要将您的resx file 命名为:
views.home.index.en-US.resx
或者您可以将create same folder structure 作为资源文件夹中的views/controller,例如:
Resources/Views/Home/Index.en.resx.
- 在您的
startup.cs 中,您需要注册支持本地化所需的服务并通过以下方式配置它们:
//in your ConfigureServices method
services.AddLocalization(opts => { opts.ResourcesPath = "Resources"; });
services.AddMvc()
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization();
和:
//in your Configure method
var supportedCultures = new[]
{
//add the cultures you support..
new CultureInfo("en-US"),
new CultureInfo("fr"),
};
app.UseRequestLocalization(new RequestLocalizationOptions
{
// Set the default culture.
DefaultRequestCulture = new RequestCulture("en-US"),
// Formatting numbers, dates, etc.
SupportedCultures = supportedCultures,
// UI strings that we have localized.
SupportedUICultures = supportedCultures
});
-
当一个请求进来时,它会通过specific middleware 来决定使用哪种文化using one of these providers:
-
QueryStringRequestCultureProvider。
-
CookieRequestCultureProvider。大多数应用都使用这种机制来保持用户文化。
-
AcceptLanguageHeaderRequestCultureProvider。
运行您的应用并使用QueryStringRequestCultureProvider 对其进行测试,例如:https://localhost:5001/?culture=fr
注意:
您需要有一个 culture fallback behavior 来处理任何不受支持的文化,方法是拥有一个不带 .Language_Code 前缀的 .resx 文件,例如:views.home.index.resx,它基本上包含您应用的主要语言。
B) 如果您觉得方法 A 太过分:
如果您只想拥有特定数量的 .resx 文件,例如:SharedResource.resx、SharedResource.fr.resx、Messages.resx、Messages.fr.resx 和 Errors.resx、Errors.fr.resx,那么您可以创建这些 @987654356 @在你的Resources folder里面。
然后在你的startup.cs:
//in your ConfigureServices method
services.AddLocalization(opts => { opts.ResourcesPath = "Resources"; });
services.AddMvc();
和:
//in your Configure method
var supportedCultures = new[]
{
//add the cultures you support..
new CultureInfo("en-US"),
new CultureInfo("fr"),
};
app.UseRequestLocalization(new RequestLocalizationOptions
{
// Set the default culture.
DefaultRequestCulture = new RequestCulture("en-US"),
// Formatting numbers, dates, etc.
SupportedCultures = supportedCultures,
// UI strings that we have localized.
SupportedUICultures = supportedCultures
});
最后,您可以使用资源文件名访问资源文件,例如:@SharedResource.Hello
注意:您需要在您的_ViewImports.cshtml 中引用资源才能在您的视图中使用它们。
我知道这是一个很长的答案,但我想为您提供 2 种不同的方法,以便您决定哪种方法最适合您的用例。