3

How do you get current culture or browser locale on MVC 4.

I find some samples which gets it from HttpContext and HttpRequest but this doesnt work on MVC 4.

How do you do it on MVC 4?

DarthVader
  • 52,984
  • 76
  • 209
  • 300

2 Answers2

13

I find some samples which gets it from HttpContext and HttpRequest but this doesnt work on MVC 4.

I just love the it doesn't work problem description!!! It's like saying to a mechanic whom you don't want to pay for the job: my car doesn't work, tell me what is wrong with it so that I can fix it myself, without showing him your car of course.

Anyway, you still got the HttpRequest in your controller action. Look at the UserLanguages property:

public ActionResult SomeAction()
{
    string[] userLanguages = Request.UserLanguages;
    ...
}

Remark: the value of this property will be null if the user agent didn't send the Accept-Languages request header. So make sure you check whether it is not null before accessing its value to avoid getting NREs.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • The array is because the browser can send multiple items, specifically when the user has configured fallback languages, as referenced here: http://stackoverflow.com/questions/8552927/what-is-q-0-5-in-accept-http-headers – Dominic Zukiewicz Jun 10 '13 at 11:27
  • Yes, exactly. That's why the `UserLanguages` property returns an array of strings. – Darin Dimitrov Jun 10 '13 at 11:28
  • You really could save all the mechanic patronizing stuff and maybe teach him how to properly make a question? Constructive feedback is always better. – Mario Lopez Oct 15 '21 at 03:52
0

We use the following code in NuGetGallery

 /// <summary>
/// Extensions on <see cref="HttpRequest"/> and <see cref="HttpRequestBase"/>
/// </summary>
public static class HttpRequestExtensions
{
    /// <summary>
    /// Retrieve culture of client. 
    /// </summary>
    /// <param name="request">Current request.</param>
    /// <returns><c>null</c> if not to be determined.</returns>
    public static CultureInfo DetermineClientCulture(this HttpRequest request)
    {
        return DetermineClientCulture(new HttpRequestWrapper(request));
    }

    /// <summary>
    /// Retrieve culture of client. 
    /// </summary>
    /// <param name="request">Current request.</param>
    /// <returns><c>null</c> if not to be determined.</returns>
    public static CultureInfo DetermineClientCulture(this HttpRequestBase request)
    {
        if (request == null)
        {
            return null;
        }

        string[] languages = request.UserLanguages;
        if (languages == null)
        {
            return null;
        }

        //first try parse of full langcodes. Stop with first success.
        foreach (string language in languages)
        {
            string lang = language.ToLowerInvariant().Trim();
            try
            {
                return CultureInfo.GetCultureInfo(lang);
            }
            catch (CultureNotFoundException)
            {
            }
        }

        //try parse again with first 2 chars.  Stop with first success.
        foreach (string language in languages)
        {
            string lang = language.ToLowerInvariant().Trim();
            if (lang.Length > 2)
            {
                string lang2 = lang.Substring(0, 2);
                try
                {
                    return CultureInfo.GetCultureInfo(lang2);
                }
                catch (CultureNotFoundException)
                {
                }
            }
        }

        return null;
    }
}

usage:

    /// <summary>
    /// Called before the action method is invoked.
    /// </summary>
    /// <param name="filterContext">Information about the current request and action.</param>
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (!filterContext.IsChildAction)
        {
            //no need to do the hassle for a child action
            //set the culture from the request headers
            var clientCulture = Request.DetermineClientCulture();
            if (clientCulture != null)
            {
                //and/or CurrentUICulture 
                Thread.CurrentThread.CurrentCulture = clientCulture;
            }
        }

        base.OnActionExecuting(filterContext);
    }
Julian
  • 33,915
  • 22
  • 119
  • 174