2011-08-24 28 views
2

我想代碼着陸頁通過閱讀文化將決定請求是否將被重定向到英文網站或斯洛伐克網站。有問題與文化和NullReferenceException

這是代碼的樣子:

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

的問題是,在瀏覽器,它看起來不錯,它會將您重定向到網站:http://www.alexmolcan.sk

但檢查IIS日誌的時候,谷歌網站管理員工具或http://www.rexswain.com/httpview.html我總是得到500 ASP錯誤:

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

響應頭:

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

當我在本地調試項目時,它始終編譯時沒有任何問題。我不知道我做錯了什麼

謝謝。

編輯

異常

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) 

回答

3

我想你扔,因爲當ResolveCountry返回null您的ToString(),如果(strcountry == 「SK」)將要拋出。

無法將null轉換爲字符串。嘗試

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

if (strCountry == "SK") {} 
+0

看起來你是對的,我要檢查加入檢查爲空 – feronovak