2011-08-24 47 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