Search code examples
c#.netasp.net-web-api2globalization

.net WebApi 2.0 - Set culture for all the user request at code level (Globalization)


I have a .net webapi 2.0 using standard .Net Framework ( not core ).

In this moment the default Culture is set in webconfig:

web.config

<system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <globalization enableClientBasedCulture="false" uiCulture="it-IT" culture="it-IT" />
  </system.web>

What I wan't to do Is provide a method where the user can switch the culture. I'm trying this code but it doesn't work...

Thread.CurrentThread.CurrentCulture = new CultureInfo(strCulture);

The culture is changed only for that thread but for the nexts it continues to get the default culture specified in webconfig....

Thanks to support


Solution

  • This is what worked for me:

    public class LanguageMessageHandler : DelegatingHandler
    {
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            // here you can chose to get the lang from database, cookie or from the request if the culture is stored on local storage.
            SetCulture(request, "ro-RO");
            return base.SendAsync(request, cancellationToken);
        }
    
        private void SetCulture(HttpRequestMessage request, string lang)
        {
            request.Headers.AcceptLanguage.Clear();
            request.Headers.AcceptLanguage.Add(new StringWithQualityHeaderValue(lang));
            Thread.CurrentThread.CurrentCulture = new CultureInfo(lang);
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(lang);
        }
    }
    

    Add the LanguageMessageHandler to MessageHandlers in WebApiConfig

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.MessageHandlers.Add(new LanguageMessageHandler()); // <- add this line
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }