Jen*_*nan 5 razor asp.net-core asp.net-core-localization
我尝试在以下项目结构中使用 Asp.Net Core 创建 Razor 类库:
我在我的网络应用程序中使用了这些设置来进行Startup课堂本地化:
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddViewLocalization(
LanguageViewLocationExpanderFormat.Suffix,
opts => { opts.ResourcesPath = "Resources"; })
.AddDataAnnotationsLocalization();
services.Configure<RequestLocalizationOptions>(
opts =>
{
var supportedCultures = new[]
{
new CultureInfo("en-US"),
new CultureInfo("en")
};
opts.DefaultRequestCulture = new RequestCulture("en");
opts.SupportedCultures = supportedCultures;
opts.SupportedUICultures = supportedCultures;
});
....
var options = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(options.Value);
Run Code Online (Sandbox Code Playgroud)
在Index.cshtml:
@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer
<h1>@Localizer["Title"]</h1>
Run Code Online (Sandbox Code Playgroud)
不幸的是,结果只是字符串“Title”。我无法从 Razor 类库加载这些 resx 文件。
如何像上面那样使用 Razor 类库中的本地化?
更新:这是非常相似的用例 - https://github.com/aspnet/Localization/issues/328 - 提供了一些示例。
您似乎忘记使用正确配置本地化AddLocalization
使用文档中提供的详细信息
配置本地化
本地化在方法中配置
ConfigureServices:
services.AddLocalization(options => options.ResourcesPath = "Resources"); //<<< This is required
services
.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization();
Run Code Online (Sandbox Code Playgroud)
AddLocalization将本地化服务添加到服务容器中。上面的代码还将资源路径设置为“Resources”。
AddViewLocalization添加对本地化视图文件的支持。
AddDataAnnotationsLocalization通过抽象添加对本地化DataAnnotations验证消息的支持IStringLocalizer。
本地化中间件
请求的当前文化是在本地化中间件中设置的。该方法中启用了本地化中间件
Configure。必须在任何可能检查请求区域性的中间件之前配置本地化中间件(例如,app.UseMvcWithDefaultRoute())。
var supportedCultures = new[] {
new CultureInfo("en-US"),
new CultureInfo("en")
};
app.UseRequestLocalization(new RequestLocalizationOptions{
DefaultRequestCulture = new RequestCulture("en"),
// Formatting numbers, dates, etc.
SupportedCultures = supportedCultures,
// UI strings that we have localized.
SupportedUICultures = supportedCultures;
});
//...other middleware
app.UseMvcWithDefaultRoute();
Run Code Online (Sandbox Code Playgroud)
示例图像中显示的资源文件的路径遵循路径命名约定,前提是您使用的是ResourcesPath设置为“资源”的选项的选项。这应该允许视图在“Resources”文件夹的相对路径中找到资源文件。
另一种方法是不使用该ResourcesPath选项,并将.resx文件放在与视图相同的文件夹中,当然要遵循命名约定。
根据提供的其他详细信息,表明 UI 项目将打包为 nuget 包。
然后将资源文件打包到nuget包中,并在安装时解压到目标项目的resources文件夹中。
资源需要位于站点根目录中才能供视图使用,因此您需要引用以下目录中的所有文件.nuspec:
services.AddLocalization(options => options.ResourcesPath = "Resources"); //<<< This is required
services
.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5685 次 |
| 最近记录: |