.Net Core 3.1 本地化在部署后不适用于 Accept-Language Header 除英语以外的其他文化
.Net Core 3.1 Localization not working with Accept-Language Header for other cultures except english after deployment
我已经按照 https://docs.microsoft.com/en-us/aspnet/core/fundamentals/localization?view=aspnetcore-3.1 在 .Net Core 3.1 中实现了本地化。它在本地使用时工作正常
QueryString 和 Accept-Language HTTP header 在本地但 部署后 无法与 Accept-Language HTTP header 一起用于英语以外的其他文化。
代码更改
- 在Startup.cs
// 在配置服务中
services.AddRazorPages()
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization()
services.AddLocalization(options => options.ResourcesPath = "Resources");
services.Configure<RequestLocalizationOptions>(options =>
{
var supportedCultures = GetSupportedCultures();
options.DefaultRequestCulture = new RequestCulture("en");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
});
// 在配置方法中
app.UseRequestLocalization(app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>().Value);
// 辅助方法
private IList<CultureInfo> GetSupportedCultures()
{
var cultures = Configuration.GetValue<string>("SupportedCultures")?.Split(",");
var supportedCultures = new List<CultureInfo>();
foreach (var culture in cultures)
{
supportedCultures.Add(new CultureInfo(culture.Trim()));
}
return supportedCultures;
}
// 在 appsettings.json
"SupportedCultures": "en,fr,de,el,es"
在浏览器网络选项卡中请求 Header
Accept-Language: fr-FR,fr-CA;q=0.9,fr;q=0.8,de;q=0.7,en;q=0.6,es;q=0.5,el;q=0.4,en-GB;q=0.3,en-US;q=0.2
我已经按照 https://docs.microsoft.com/en-us/aspnet/core/fundamentals/localization?view=aspnetcore-3.1 在 .Net Core 3.1 中实现了本地化。它在本地使用时工作正常 QueryString 和 Accept-Language HTTP header 在本地但 部署后 无法与 Accept-Language HTTP header 一起用于英语以外的其他文化。 代码更改
- 在Startup.cs
// 在配置服务中
services.AddRazorPages()
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization()
services.AddLocalization(options => options.ResourcesPath = "Resources");
services.Configure<RequestLocalizationOptions>(options =>
{
var supportedCultures = GetSupportedCultures();
options.DefaultRequestCulture = new RequestCulture("en");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
});
// 在配置方法中
app.UseRequestLocalization(app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>().Value);
// 辅助方法
private IList<CultureInfo> GetSupportedCultures()
{
var cultures = Configuration.GetValue<string>("SupportedCultures")?.Split(",");
var supportedCultures = new List<CultureInfo>();
foreach (var culture in cultures)
{
supportedCultures.Add(new CultureInfo(culture.Trim()));
}
return supportedCultures;
}
// 在 appsettings.json
"SupportedCultures": "en,fr,de,el,es"
在浏览器网络选项卡中请求 Header
Accept-Language: fr-FR,fr-CA;q=0.9,fr;q=0.8,de;q=0.7,en;q=0.6,es;q=0.5,el;q=0.4,en-GB;q=0.3,en-US;q=0.2