【问题标题】:Localization doesn't work on production - .NET core 3.1本地化不适用于生产 - .NET core 3.1
【发布时间】:2021-05-10 14:46:13
【问题描述】:

我正在为我的 API 应用程序使用本地化。问题是,在本地机器上一切正常,但是当我在 Azure 上部署应用程序时,本地化不再工作了。

这是请求调试时的结果(消息已翻译):

{
  "status": "NotFound",
  "timestamp": "2021-05-05T03:31:10Z",
  "code": "R001",
  "message": "Customer order was not found!"
}

这是请求生产时的结果(消息显示为键 - R001,而不是翻译值):

{
  "status": "NotFound",
  "timestamp": "2021-05-05T03:29:04Z",
  "code": "R001",
  "message": "R001"
}

我不知道出了什么问题。

项目层次结构如下: enter image description here

我的 CustomerOrder/Startup.cs:

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

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    ...
    // adding culture
    var supportedCultures = new List<CultureInfo>
    {
        new CultureInfo("fr"),
        new CultureInfo("fr-FR"),
        new CultureInfo("en"),
        new CultureInfo("en-US")
    };

    var localizationOptions = new RequestLocalizationOptions
    {
        DefaultRequestCulture = new RequestCulture("en"),
        // formatted numbers, dates, etc
        SupportedCultures = supportedCultures,
        // UI strings that we have localized
        SupportedUICultures = supportedCultures,
    };
    app.UseRequestLocalization(localizationOptions);
}

我如何在控制器中使用本地化

...
private readonly IStringLocalizer<CustomerOrdersController> _localizer;
...
_localizer["R001"]

天蓝色管道上的任务

  - task: DotNetCoreCLI@2
    inputs:
      command: 'build'
      projects: '$(build.sourcesDirectory)/src/$(projectName)/$(projectName).csproj'
      arguments: '-c "$(buildConfiguration)" -f "netcoreapp3.1" -r "ubuntu.19.10-x64"'

【问题讨论】:

    标签: azure asp.net-core-3.1 asp.net-core-localization


    【解决方案1】:

    最后,我自己解决了这个问题。

    构建解决方案时似乎目标命名空间不正确,因此将资源文件(.resx)的Custom Tool NameSpace属性更改为CustomerOrder即可解决问题.

    在 VS 2019 中:

    1. 右键单击 .resx 文件,选择属性。
    2. 将 Custom Tool NameSpace 属性更改为目标项目命名空间(在我的例子中,CustomerOrder 是目标项目)。

    或者更简单的方法,将以下配置添加到 .csproj 文件(包含资源文件的项目,在我的例子中是 CustomerOrder.Api.csproj)

    <ItemGroup>
      <EmbeddedResource Update="Resources\**">
        <CustomToolNamespace>CustomerOrder</CustomToolNamespace>
      </EmbeddedResource>
    </ItemGroup>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-12
      • 1970-01-01
      • 1970-01-01
      • 2020-05-05
      • 1970-01-01
      • 2020-04-22
      • 2016-11-08
      • 1970-01-01
      相关资源
      最近更新 更多