Cannot determine if Session variable exists

I am trying to determine if a Session variable exists, but I get an error:

System.NullReferenceException: An object reference is not set to an instance of the object.

the code:

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

This is because the Session name "company_path" does not exist, but I cannot detect it!

+7
source share
2 answers

Do not use ToString () if you want to check if Session ["company_path"] is null. Like if Session["company_path"] is null then Session["company_path"].ToString() will give you exception.

Edit

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

For

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

If deploying to Azure (as of August 2017), it is also useful to check if the session key array is full, for example:

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

All Articles