Search code examples
asp.net-mvcmultilingual

How to show my home page in the browser's preferred language using ASP.NET MVC


I want to create a multi language website. I found out that one way to do it is to display the webpage in their own language based on the preferred language of user's browser. I tried the code below and it seems it works fine.

public ActionResult Index()
    {

        var userLanguages = Request.UserLanguages;
        string preferredLanguage = "";

        preferredLanguage = userLanguages[0];

        if (preferredLanguage == "fr-FR") 

        {

            return RedirectToAction("fr", "Home");
        }
        else 
        {
            return RedirectToAction("en", "Home");
        }

    }

I thought this was very simple and so I searched around and found this link

I am a little confused - should I add this code and what exactly does it do? When I debug the code I find every time that ci is null. How should I use 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

Appreciate any help.

with the help of Alex, its my code right now, It works well but I am worried about possible extensions

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");
    }

Solution

  • Try this.

    public ActionResult Index()
    {
        CultureInfo ci;
        var userLanguages = Request.UserLanguages;
    
        if (userLanguages.Count() > 0)
        {
            try
            {
                ci = new CultureInfo(userLanguages[0]);
            }
            catch (CultureNotFoundException)
            {
                ci = CultureInfo.InvariantCulture;
            }
        }
        else
        {
            ci = CultureInfo.InvariantCulture;
        }
    
        return RedirectToAction(ci.TwoLetterISOLanguageName, "Home");
    }
    

    The TwoLetterISOLanguageName gets the two letter language code (e.g. fr-FR = fr). This avoids the if...else statement for the redirect.