区域性和NullReferenceException有问题

本文关键字:有问题 NullReferenceException 区域性 | 更新日期: 2023-09-27 18:06:30

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

代码是这样的:

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)

区域性和NullReferenceException有问题

我认为你正在抛出,因为当resolveccountry返回null时,你的。tostring()和if(strcountry == "SK")将抛出。

不能将null转换为字符串。试着

CultureInfo cul = ResolveCountry();
string strCountry = cul== null ? string.empty : cul.ToString();
if (strCountry == "SK") {}