0

I have found this link as a guide to make a multi language website which it should run with users preferred language which they have set on their browsers.

Get CultureInfo from current visitor and setting resources based on that?

as you see it has this code to do it

// Get Browser languages.
 var userLanguages = Request.UserLanguages;
 CultureInfo ci;
 if (userLanguages.Count() > 0)
  {
   try
    {
      ci = new CultureInfo(userLanguages[0]);
    }
   catch(CultureNotFoundException)
    {
     ci = CultureInfo.InvariantCulture;
    }
   }
    else
     {
        ci = CultureInfo.InvariantCulture;
     }
    // Here CultureInfo should already be set to either user's preferable language
   // or to InvariantCulture if user transmitted invalid culture ID

but my question is that I do not know what exactly is the duty of CultureInfo.InvariantCulture and it does not work at all in my project. it is always null.

I changed the code to this , It works fine but I am not sure about possible exceptions may it have. I really appreciate any kind of help. here is what I have and it works completely fine but just not sure about possible exceptions. I want the default language to be "en-US"

  public ActionResult Index()
{
    CultureInfo ci;
    var userLanguages = Request.UserLanguages;


    if (userLanguages == null)
    {
        ci = new CultureInfo("en-US");
    }

    else if (userLanguages.Count() > 0)
    {
        try
        {
            ci = new CultureInfo(userLanguages[0]);
        }
        catch (CultureNotFoundException)
        {
            ci = new CultureInfo("en-US");
        }
    }
    else
    {
        ci = new CultureInfo("en-US");
    }

    return RedirectToAction(ci.TwoLetterISOLanguageName, "Home");
}
neda Derakhshesh
  • 1,103
  • 2
  • 20
  • 43

1 Answers1

1

Your code look fine, if user transmitted invalid culture ID it will use the "en-US" culture!

The CultureInfo.InvariantCulture property is used if you are formatting or parsing a string that should be parseable by a piece of software independent of the user's local settings.

The default value is CultureInfo.InstalledUICulture so the default CultureInfo is depending on the executing OS's settings.

The code bellow should work as well to set the culture:

    private static bool DoesCultureExist(string cultureName)
    {
        return CultureInfo.GetCultures(CultureTypes.AllCultures).Any(culture => string.Equals(culture.Name, cultureName, StringComparison.CurrentCultureIgnoreCase));
    }
    public ActionResult Index()
    {
        CultureInfo ci;
        var userLanguages = Request.UserLanguages;

        if (DoesCultureExist(userLanguages?[0]))
        {
            ci = new CultureInfo(userLanguages[0]);
        }
        else
        {
            ci = new CultureInfo("en-US");
        }

        return RedirectToAction(ci.TwoLetterISOLanguageName, "Home");
    }
Yanga
  • 2,885
  • 1
  • 29
  • 32