razor - 如何在 Asp.Net Core 中的 Razor 类库中使用本地化

标签 razor asp.net-core asp.net-core-localization

我尝试在以下项目结构中使用 Asp.Net Core 创建 Razor 类库:

enter image description here

我已在我的 Web 应用程序中使用这些设置在 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);

Index.cshtml中:

@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer


<h1>@Localizer["Title"]</h1>

不幸的是,结果只是字符串“Title”。我无法从 Razor 类库加载这些 resx 文件。

如何像上面一样使用 Razor 类库中的本地化?

更新:这是非常相似的用例 - https://github.com/aspnet/Localization/issues/328 - 这提供了一些例子。

最佳答案

我还没有尝试过接受的答案,并且根据评论,OP似乎没有让它发挥作用。我实现了一种类似于 MVC/Razor Pages 使用的 View /页面定位器模式的模式,即可以在 RCL 或单独的程序集中提供资源并使用 ViewLocalizer,它只会找到匹配的资源来自最高优先级资源的字符串。您可以阅读我的实现,看看它是否适合您。

https://terryaney.wordpress.com/2021/01/04/migrating-to-net-core-overridable-localization-in-razor-class-libraries/

关于razor - 如何在 Asp.Net Core 中的 Razor 类库中使用本地化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50841085/

相关文章:

asp.net-mvc-3 - 安装 MVC4 beta 似乎破坏了 MVC3 应用程序

c# - 在 Razor Pages 中调用操作

javascript - 在单引号内返回 @Html.DropDownListFor 内的 ViewBag

asp.net-web-api - 如何在 Kubernetes 的 pod 中限制 .net core 应用程序的内存大小?

asp.net-core - 如何在 Visual Studio 2015 RC 中为 ASP.NET 5 MVC 6 项目设置 TypeScript 编译器版本?

c# - 登录后覆盖.Net Core "CultureInfo"

c# - ASP.NET CORE (.NET Framework) 和本地化

jquery - 如何在 mvc razor 中显示/隐藏网格行

asp.net-core - ASP.NET Core : A compatible SDK version for global. json 版本 2.1.400 未找到

c# - 如何使用默认本地化创建用于本地化的 SharedResource 类