【问题标题】:ASP.NET Core 2 Localization (ViewLocalizer Not Working)ASP.NET Core 2 本地化(ViewLocalizer 不工作)
【发布时间】:2018-02-11 00:21:41
【问题描述】:

我有以下几点:

public void ConfigureServices(IServiceCollection services)
{
   ...
   services.AddLocalization(o => { o.ResourcesPath = "Resources"; });
   services.AddMvc(options =>{})
   .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
   .AddDataAnnotationsLocalization();
 }

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    IList<CultureInfo> supportedCultures = new List<CultureInfo>
    {
       new CultureInfo("en"),
       new CultureInfo("ko"),
     };
     app.UseRequestLocalization(new RequestLocalizationOptions
     {
        DefaultRequestCulture = new RequestCulture("en"),
        SupportedCultures = supportedCultures,
        SupportedUICultures = supportedCultures
      });
      ......
}

我有一个Index.cshtml,其中包含以下内容(位于/Views/Home/ 内)。

@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer
......
<h2>@Localizer["QuickLinksTitle"].Value</h2>

我有 2 个 .resx 文件,Index.en.resxIndex.ko.resx/Resources/Views/Home

但是视图总是显示QuickLinksTitle而不是.resx文件中的值。

.resx 都有键 QuickLinksTitle 和相应的文本值,但它似乎从不从任何资源文件中读取任何内容。

我已验证我的浏览器确实发送了正确的语言Accept-Language: ko,en-US;q=0.9,en;q=0.8

我的假设是,如果我给出@Localizer['Key'],它应该是读取该键的值,而不是实际的键。

我知道 MS 希望我们做 @Localizer["Some text in default lang"],然后它有非默认语言的密钥,但我更喜欢有一个 .resx 用于默认语言(英语),一个用于其他语言。但现在我什至还没有从.resx 文件中读取数据。

【问题讨论】:

    标签: c# asp.net-mvc asp.net-core localization .net-core


    【解决方案1】:

    我了解 MS 希望我们使用 @Localizer["Some text in default lang"],然后它具有非默认语言的密钥,但我更喜欢为默认语言(英语)设置一个 .resx,为其他所有语言设置一个。

    这是可行的。但是,您需要遵循在.resx 文件中使用默认语言的约定。

    您已将默认语言设置为en

    app.UseRequestLocalization(new RequestLocalizationOptions
    {
        DefaultRequestCulture = new RequestCulture("en"),
        SupportedCultures = supportedCultures,
        SupportedUICultures = supportedCultures
    });
    

    但是您已经为en 设置了一个本地化 .resx 文件:

    /Resources/Views/Home/Index.en.resx
    /Resources/Views/Home/Index.ko.resx
    

    它应该是一个 default .resx 默认语言 en 的文件:

    /Resources/Views/Home/Index.resx
    /Resources/Views/Home/Index.ko.resx
    

    【讨论】:

    • 看来我的问题实际上是 AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix) 将其更改为 SubFolder 并且似乎工作正常。
    • 我有同样的问题,但子文件夹对我没有任何想法?
    • 对我来说,将其更改为 LanguageViewLocationExpanderFormat.SubFolder 也很有帮助。但这看起来像是 asp.net 中的一个错误。
    猜你喜欢
    • 2018-04-15
    • 2021-01-20
    • 2017-01-06
    • 2016-10-16
    • 1970-01-01
    • 1970-01-01
    • 2017-09-02
    • 2020-11-29
    • 1970-01-01
    相关资源
    最近更新 更多