Reputation: 2552
I have a .net webapi 2.0 using standard .Net Framework ( not core ).
In this moment the default Culture is set in webconfig:
<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
Upvotes: 1
Views: 2361
Reputation: 58
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 }
);
}
}
Upvotes: 3