Good way to dynamically change language resources on request

I have an ASP.NET Web API application that should respond appropriately to the user's Accept-Language header.

Currently, strings are stored in resx and are accessible by compilation using the Visual Studio class. What I would like to do is keep the current approach and create satellite assemblies for each translated resx version. Then analyze the user's Accept-Language header to find out which languages ​​the user accepts and downloads resources for the requested language from the satellite assembly.

I assume that I was able to realize all this myself by creating a set of language-specific ResourceManager objects using a ResourceSet , but then it would be impossible to maintain security at compile time, since Visual Studio would take care of automatically updating the class for the resx file.

What would be the best way to select a localized language resource dynamically?

+6
source share
2 answers

From reading your question, I see nothing that ASP.NET does not automatically offer. You can configure ASP.NET (whether WebForms or MVC) to use the accept-language request header and set the appropriate UICulture (which will affect the assembly of ResourceManager satellites) and Culture (which will affect language-specific formatting and parsing such as dates and numbers )

To configure the application to use the accept-language list to install both UICulture and Culture for each request (according to this MSDN page ), configure your network. config as follows:

 <globalization uiCulture="auto" culture="auto" /> 

There is also an equivalent configuration setting per page.

Then, according to the Return Resources process, if your application includes assembling satellites for the appropriate culture (or, otherwise, its parent neutral culture), this will be used by the resource manager. If not, then your default resources will be used (in English if this is your base language).

+10
source

You can write an HttpModule that defines the language header and sets the current stream culture.

 public class LanguageModule : IHttpModule { public void Dispose() { } public void Init(HttpApplication context) { context.BeginRequest += new EventHandler(context_BeginRequest); } void context_BeginRequest(object sender, EventArgs e) { var application = sender as HttpApplication; var context = application.Context; var lang = context.Request.Headers["Accept-Language"]; // eat the cookie (if any) and set the culture if (!string.IsNullOrEmpty(lang)) { var culture = new System.Globalization.CultureInfo(lang); // you may need to interpret the value of "lang" to match what is expected by CultureInfo Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentUICulture = culture; } } } 

ResourceManager et al. Find out the correct localized version to use from the thread culture.

+2
source

Source: https://habr.com/ru/post/918333/


All Articles