Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change site language using Resources and CultureInfo in ASP .NET MVC?

Tags:

c#

asp.net-mvc

I have several resource files for each language I want to support, named like below:

NavigationMenu.en-US.resx
NavigationMenu.ru-RU.resx
NavigationMenu.uk-UA.resx

Files are located in MySolution/Resources/NavigationMenu folder.

I have action which sets CurrentCulture and CurrentUICulture like below

public ActionResult SetLanguage(string lang)
{
    try
    {
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang);
        Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(lang);
        return Redirect(Request.UrlReferrer.AbsoluteUri);
    }
    catch(Exception)
    {
        return RedirectToAction("Index");
    }
}

lang parameter values are uk-UA, ru-RU or en-US depending on what link in my view was clicked. Also I have web config globalization defined section:

<globalization requestEncoding="utf-8" responseEncoding="utf-8" culture="ru-RU" uiCulture="ru-RU" />

When my application starts I have Russian language as expected but when I try to change my language with SetLanguage action to English I get no language changes in my views. NavigationMenu.SomeProperty is still Russian. What am I missing?

like image 769
Dmytro Avatar asked Feb 16 '23 09:02

Dmytro


1 Answers

You are updating the culture for the current thread only.

Most sites support localization by including this as part of their URL (in all pages). And with MVC, you can implement this approach by processing the culture using an action filter. This answer has a good solution for this.

Aside from this, you would need to implement this by either persisting the culture to the session or a cookie, and then updating the thread's culture on every request, again by implementing an action filter, or during an application event that contains the request context, such as AquireRequestState.

like image 101
Jerad Rose Avatar answered Apr 09 '23 23:04

Jerad Rose