问题
I have an asp.net core project where I want to set the default language to nl-BE. For some reason it always take the language en-US
See code below (ps: I created my own ApplicationLocalizer who fetched the resources from a database => works fine).
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);
...
}
A controller
public string Index()
{
return CultureInfo.CurrentCulture.Name;
}
This snippet of code always returns en-US
Can someone help me solve this problem?
回答1:
After hours of searching for solution with no result, I went for heavy debugging and realized that the middleware services are executed in an order as declared in the Configure(IApplicationBuilder app...). Therefore the localization middleware was invoked after the controller action was executed.
When I moved the app.UseRequestLocalization(options) invocation at the very beginning I got properly localized Thread/CultureInfo in controller actions.
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);
}
来源:https://stackoverflow.com/questions/40997851/always-same-culture-en-us