feronovak
feronovak

Reputation: 2697

Having problem with Culture and NullReferenceException

I am trying to code landing page which by reading Culture will decide whether request will be redirected to English site or Slovak site.

This is what the code looks like:

public partial class _default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string strCountry = ResolveCountry().ToString();
        if (strCountry == "SK")
        {
            Response.Redirect("/sk/");
        }
        else
        {
            Response.Redirect("/en/");
        }
    }

    public static CultureInfo ResolveCulture()
    {
        string[] languages = HttpContext.Current.Request.UserLanguages;

        if (languages == null || languages.Length == 0)
            return null;

        try
        {
            string language = languages[0].ToLowerInvariant().Trim();
            return CultureInfo.CreateSpecificCulture(language);
        }
        catch (ArgumentException)
        {
            return null;
        }
    }

    public static RegionInfo ResolveCountry()
    {
        CultureInfo culture = ResolveCulture();
        if (culture != null)
            return new RegionInfo(culture.LCID);

        return null;
    }
}

The problem is that in browser it looks ok, it redirects you to the site: http://www.alexmolcan.sk

But when checking IIS log, Google Webmaster tools or http://www.rexswain.com/httpview.html I always get 500 ASP Error:

 Object·reference·not·set·to·an·instance·of·an·object.
 System.NullReferenceException:·Object·reference·not·set·to·an·instance·of·an·object.

Response header:

HTTP/1.1·500·Internal·Server·Error
Connection:·close
Content-Length:·4684

When I debug project locally it always compile without any problems. I don't know what I do wrong

Thank you.

EDIT

Exception

Process information: 
   Process ID: 4068 
   Process name: w3wp.exe 
   Account name: IIS APPPOOL\ASP.NET v4.0 

Exception information: 
   Exception type: NullReferenceException 
   Exception message: Object reference not set to an instance of an object.
   at sk_alexmolcan._default.Page_Load(Object sender, EventArgs e) in default.aspx.cs:line 15
   at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
   at System.Web.UI.Control.LoadRecursive()
   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean  includeStagesAfterAsyncPoint)

Upvotes: 1

Views: 1173

Answers (1)

Dustin Davis
Dustin Davis

Reputation: 14585

I think you're throwing because when ResolveCountry returns null your .ToString() and if(strcountry == "SK") is going to throw.

Can't turn null into a string. try

CultureInfo cul = ResolveCountry();
string strCountry = cul== null ? string.empty : cul.ToString();

if (strCountry == "SK") {}

Upvotes: 3

Related Questions