Search code examples
asp.netasp.net-mvcglobalizationcultureinfoculture

Get selected (active) language on browser


There is a nice thread here: Get CultureInfo from current visitor

Explaining that we can easily get the browser languages using:

var userLanguages = Request.UserLanguages;

The problem here is that this only gives me the languages configured in the browser, but not the selected one. At the same time, the first language in the array ([0]), might not be the active one.

Is there a way to find the active one on the server-side? I know I could do it on the client side using javascript, but I want to avoid double-calls.


Solution

  • You will need to set this information via a cookie (which can be toggled by a setting on your page).

    public ActionResult SetCulture(string culture) //culture is something like en-US, you can validate it ahead of time.
    {
        HttpCookie cookie = Request.Cookies["currentCulture"];
        if (cookie != null)
            cookie.Value = culture;   // update cookie value
        else //create the cookie here
        {
            cookie = new HttpCookie("currentCulture");
            cookie.Value = culture;
            cookie.Expires = DateTime.Now.AddYears(1);
        }
        Response.Cookies.Add(cookie);
        return Redirect(Request.UrlReferrer.ToString()); //send them back to the site they were at (in a translated form).
    }
    

    To determine the culture on the server side, just read the cookie when you execute an action.

    protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)
    {
    
        HttpCookie cultureCookie = Request.Cookies["currentCulture"];
        string cultureName = cultureCookie== null ? "en-US" : cultureCookie.Value;        
        if (cultureCookie != null)
            cultureName = cultureCookie.Value;
    
        // Modify current thread's cultures            
        Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(cultureName);
        Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
    
        return base.BeginExecuteCore(callback, state);
    }