我正在为我的 API 应用程序使用本地化。问题是,一切在本地计算机上运行良好,但是当我在 Azure 上部署应用程序时,本地化不再起作用。
这是请求调试时的结果(消息已翻译):
{
"status": "NotFound",
"timestamp": "2021-05-05T03:31:10Z",
"code": "R001",
"message": "Customer order was not found!"
}
这是生产请求时的结果(消息显示为 key - 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);
}
如何在 Controller 中使用本地化
...
private readonly IStringLocalizer<CustomerOrdersController> _localizer;
...
_localizer["R001"]
azure 管道上的任务
- task: DotNetCoreCLI@2
inputs:
command: 'build'
projects: '$(build.sourcesDirectory)/src/$(projectName)/$(projectName).csproj'
arguments: '-c "$(buildConfiguration)" -f "netcoreapp3.1" -r "ubuntu.19.10-x64"'
最佳答案
最后,我自己解决了这个问题。
构建解决方案时目标命名空间似乎不正确,因此将资源文件 (.resx) 的 Custom Tool NameSpace 属性更改为 CustomerOrder 已解决该问题.
在 VS 2019 中:
- 右键单击 .resx 文件,选择属性。
- 将自定义工具命名空间属性更改为目标项目命名空间(在我的例子中,CustomerOrder是目标项目)。
或者更简单的方法,将以下配置添加到 .csproj 文件(包含资源文件的项目,在我的例子中为 CustomerOrder.Api.csproj)
<ItemGroup>
<EmbeddedResource Update="Resources\**">
<CustomToolNamespace>CustomerOrder</CustomToolNamespace>
</EmbeddedResource>
</ItemGroup>
关于azure - 本地化不适用于生产 - .NET core 3.1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67394943/