Search code examples
c#asp.netlocaleasp.net-core

How do I set the locale for an ASP.NET 5 application?


I’m trying to do a blanket override of the host locale for an ASP.NET 5 web application. Most solutions refer to the <globalization/> web.config element, but this is IIS-specific and doesn't seem to fit the new ASP.NET model.

I tried:

app.Use(next => context => {
    Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-AU");
    Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-AU");
    return next(context);
});

This gets executed, but this doesn’t seem to have any effect on the request (maybe due to the extensive Tasking in the pipeline?) Is there a better way to accomplish this?


Solution

  • The issue is with the async controller. You should set the default culture to all threads instead:

    app.Use(next => context => {
        CultureInfo.DefaultThreadCurrentCulture = CultureInfo.GetCultureInfo("en-AU");
        CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.GetCultureInfo("en-AU");
    
        return next(context);
    });
    

    You can actually just put these lines at the top of the Configure method:

    CultureInfo.DefaultThreadCurrentCulture = CultureInfo.GetCultureInfo("en-AU");
    CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.GetCultureInfo("en-AU");