我有一个asp.net核心项目,我想将默认语言设置为nl-BE。出于某种原因,它总是采用en-US语言
请参阅下面的代码(ps:我创建了自己的ApplicationLocalizer,它从数据库中获取资源=>工作正常)。
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
//Add MVC
services.AddMvc()
.AddViewLocalization();
//Localization factory
services.AddSingleton<IStringLocalizerFactory, ApplicationLocalizerFactory>();
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ApplicationDbContext context)
{
...
//Localization
var supportedCultures = new[]
{
new CultureInfo("en-US"),
new CultureInfo("nl-BE")
};
var options = new RequestLocalizationOptions {
DefaultRequestCulture = new RequestCulture("nl-BE"),
SupportedCultures = supportedCultures,
SupportedUICultures = supportedCultures
};
app.UseRequestLocalization(options);
...
}
控制器
public string Index()
{
return CultureInfo.CurrentCulture.Name;
}
这段代码始终返回 en-US
有人可以帮我解决这个问题吗?
答案 0 :(得分:1)
在没有结果的情况下搜索解决方案数小时之后,我进行了大量调试并意识到中间件服务是按配置(IApplicationBuilder应用程序...中声明的顺序执行的。 )即可。因此,在执行控制器操作之后,调用了本地化中间件。
当我在开始时移动 app.UseRequestLocalization(options)调用时,我在控制器操作中得到了正确的本地化Thread / CultureInfo。
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory,
IApplicationLifetime appLifetime)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
// THIS HAS TO BE A VERY FIRST MIDDLEWARE REGISTRATION
SetUpLocalization(app);
app.UseCors("AllowAllOrigins");
app.UseMvc();
appLifetime.ApplicationStopped.Register(() => ApplicationContainer.Dispose());
}
private static void SetUpLocalization(IApplicationBuilder app)
{
var supportedCultures = new[]
{
new CultureInfo("en-US"),
new CultureInfo("pl-PL"),
new CultureInfo("pl")
};
var options = new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture("en-US", "en-US"),
SupportedCultures = supportedCultures,
SupportedUICultures = supportedCultures
};
// Configure the Localization middleware
app.UseRequestLocalization(options);
}