7

我试图确定是否Session变量存在,但我得到的错误:无法检测会话变量是否存在

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

代码:

// Check if the "company_path" exists in the Session context 
    if (System.Web.HttpContext.Current.Session["company_path"].ToString() != null) 
    { 
     // Session exists, set it 
     company_path = System.Web.HttpContext.Current.Session["company_path"].ToString(); 
    } 
    else 
    { 
     // Session doesn't exist, set it to the default 
     company_path = "/reflex/SMD"; 
    } 

这是因为Session名称“company_path”不存在,但我无法检测到它!

回答

22

如果要检查Session [“company_path”]是否为空,则不要使用ToString()。作为if Session["company_path"] is null then Session["company_path"].ToString() will give you exception.

变化

if (System.Web.HttpContext.Current.Session["company_path"].ToString() != null) 
{ 
    company_path = System.Web.HttpContext.Current.Session["company_path"].ToString(); 
} 
else 
{ 
    company_path = "/reflex/SMD"; 
} 

if (System.Web.HttpContext.Current.Session["company_path"]!= null) 
{ 
     company_path = System.Web.HttpContext.Current.Session["company_path"].ToString(); 
} 
else 
{ 
     company_path = "/reflex/SMD"; 
} 
+0

感谢您的回答,我仍然收到相同的错误 – Luke

+0

检查您的当前线程是否可以访问System.Web.HttpContext? – Adil

+1

如何检查?我有'使用System.Web'?这是正确的吗? – Luke

0

如果部署到Azure上(8月2017),它是有用的也检查会话密钥阵列填充,例如:

Session.Keys.Count > 0 && Session["company_path"]!= null