locked
Page.Request.UserLanguages returning null RRS feed

  • Question

  • User-1915511747 posted

    Hi,

    I have written a code to get the user language 

    currentLanguage = Page.Request.UserLanguages[0];

    But when I run the code it gives the error "Object reference not set to the instance of the object.". When I debuged I found that  Page.Request.UserLanguages[0] is returning null.

    I have IE 8 installed on my machine.

    Could anyone please help.

    Thanks in advance.

    Regards,

    Afreen

    Monday, May 14, 2012 12:52 AM

Answers

  • User1630798415 posted

    Look for the <globalization> section in web.config (which is global obviously) or the Culture and UICulture attributes on the @Page directive.

    You can also do this manually in your code by looking at Browser.UserLanguages which returns all the user's browser languages that are configured in her browser

     

    /// <summary> 
    /// Sets a user's Locale based on the browser's Locale setting. If no setting 
    /// is provided the default Locale is used. 
    /// </summary> 
    public static void SetUserLocale(string CurrencySymbol, bool SetUiCulture) 
    { 
        HttpRequest Request = HttpContext.Current.Request; 
        if (Request.UserLanguages == null) 
            return; 
     
        string Lang = Request.UserLanguages[0]; 
        if (Lang != null) 
        { 
            // *** Problems with Turkish Locale and upper/lower case 
            // *** DataRow/DataTable indexes 
            if (Lang.StartsWith("tr")) 
                return; 
     
            if (Lang.Length < 3) 
                Lang = Lang + "-" + Lang.ToUpper(); 
            try 
            { 
                System.Globalization.CultureInfo Culture = new System.Globalization.CultureInfo(Lang); 
                if (CurrencySymbol != null && CurrencySymbol != "") 
                    Culture.NumberFormat.CurrencySymbol = CurrencySymbol; 
                 
                System.Threading.Thread.CurrentThread.CurrentCulture = Culture; 
     
                if (SetUiCulture) 
                    System.Threading.Thread.CurrentThread.CurrentUICulture = Culture; 
            } 
            catch 
            { ;} 
        } 
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, May 15, 2012 12:15 AM

All replies

  • User1630798415 posted

    you can avoid this null reference exception, by using following code

    int count;
    String[] userLang = Request.UserLanguages;    
     
    for (count = 0; count < userLang.Length; count++) 
    {
       Response.Write("User Language " + count +": " + userLang[count] + "<br>");
    }

    before this have you set default culture? If not you can use following steps to set culture

    1.   Create a HttpModule to step into the request pipeline and set the thread’s culture.  Below shows the module I use.  Notice the order of precedence for getting language.  I first check cookie, then query string, and final browser language.  The key to getting the application to use the correct culture is the lines where we set Thread.CurrentThread culture properties.  Finally I store whatever value I find back in a cookie for the next time.

    using System.Globalization;
    using System.Web;
    using System.Threading;

    namespace MyAssembly {
    public class LocalizationModule : IHttpModule
    {
    private static readonly string LANGUAGE_CULTURE_PARAM = "lang";
    private static readonly CultureInfo DEFAULT_CULTURE = new CultureInfo("en");

    public void Dispose() { }

    public void Init(HttpApplication context)
    {
    context.PreRequestHandlerExecute += new System.EventHandler(context_PreRequestHandlerExecute);
    }

    void context_PreRequestHandlerExecute(object sender, System.EventArgs e)
    {
    HttpRequest request = HttpContext.Current.Request;
    HttpCookie cookie = request.Cookies[LANGUAGE_CULTURE_PARAM];
    string lang = null;
    CultureInfo ci;

    if (cookie != null) // check cookie first
    lang = request.Cookies[LANGUAGE_CULTURE_PARAM].Value;
    else if (request.QueryString[LANGUAGE_CULTURE_PARAM] != null) // chceck query string second
    lang = request.QueryString[LANGUAGE_CULTURE_PARAM];
    else if (request.UserLanguages.Length > 0) // check browser language third
    lang = request.UserLanguages[0];

    // don't do this if you are using sub cultures like en-GB
    lang = lang == null ? DEFAULT_CULTURE.Name : lang.Split('-')[0];

    try
    {
    ci = new CultureInfo(lang);
    }
    catch
    {
    ci = DEFAULT_CULTURE;
    }
    // set thread's culture properties
    Thread.CurrentThread.CurrentCulture = ci;
    Thread.CurrentThread.CurrentUICulture = ci;
    // store cookie value for user's preference
    if (cookie == null)
    {
    cookie = new HttpCookie(LANGUAGE_CULTURE_PARAM, ci.TwoLetterISOLanguageName);
    HttpContext.Current.Response.AppendCookie(cookie);
    }
    else
    cookie.Value = lang;

    cookie.Path = "/";
    }
    }}

    2.  The last task is to register the module in the web.config file.  Below shows the configuration under the system.web section of the configuration file.

    <system.web>
    ...
    <httpModules>
    <add name="LocalizationModule" type="MyAssembly.LocalizationModule, MyAssembly" />
    </httpModules>
    ...
    </system.web>
    Monday, May 14, 2012 1:12 AM
  • User-1915511747 posted

    Thanks Santosh for your response.

    I have already taken to handle the null exception, only the problem is that the code is not able to read the user language.

    Do you have some idea, why ASP.NET is not able to access the user language setting?

    Thanks & regards,

    Afreen

    Monday, May 14, 2012 1:36 AM
  • User1630798415 posted

    Look for the <globalization> section in web.config (which is global obviously) or the Culture and UICulture attributes on the @Page directive.

    You can also do this manually in your code by looking at Browser.UserLanguages which returns all the user's browser languages that are configured in her browser

     

    /// <summary> 
    /// Sets a user's Locale based on the browser's Locale setting. If no setting 
    /// is provided the default Locale is used. 
    /// </summary> 
    public static void SetUserLocale(string CurrencySymbol, bool SetUiCulture) 
    { 
        HttpRequest Request = HttpContext.Current.Request; 
        if (Request.UserLanguages == null) 
            return; 
     
        string Lang = Request.UserLanguages[0]; 
        if (Lang != null) 
        { 
            // *** Problems with Turkish Locale and upper/lower case 
            // *** DataRow/DataTable indexes 
            if (Lang.StartsWith("tr")) 
                return; 
     
            if (Lang.Length < 3) 
                Lang = Lang + "-" + Lang.ToUpper(); 
            try 
            { 
                System.Globalization.CultureInfo Culture = new System.Globalization.CultureInfo(Lang); 
                if (CurrencySymbol != null && CurrencySymbol != "") 
                    Culture.NumberFormat.CurrencySymbol = CurrencySymbol; 
                 
                System.Threading.Thread.CurrentThread.CurrentCulture = Culture; 
     
                if (SetUiCulture) 
                    System.Threading.Thread.CurrentThread.CurrentUICulture = Culture; 
            } 
            catch 
            { ;} 
        } 
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, May 15, 2012 12:15 AM