有Culture和NullReferenceException的问题

时间:2011-08-24 20:27:29

标签: c# redirect cultureinfo

我正在尝试编写着陆页,通过阅读文化将决定是否将请求重定向到英语网站或斯洛伐克网站。

这就是代码的样子:

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日志,Google网站管理员工具或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)

1 个答案:

答案 0 :(得分:3)

我认为你正在投掷,因为当ResolveCountry返回null时你的.ToString()和if(strcountry ==“SK”)将要抛出。

无法将null转换为字符串。尝试

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

if (strCountry == "SK") {}
相关问题