Can’t detect whether Session variable exists

I’m trying to determine if a Session variable exists, but I’m getting the error:

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

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

That is because the Session name “company_path” doesn’t exist, but I can’t detect it!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Change

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

To

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

Method 2

This can be solved as a one liner in the latest version of .NET using a null-conditional ?. and a null-coalesce ??:

// Check if the "company_path" exists in the Session context
company_path = System.Web.HttpContext.Current.Session["company_path"]?.ToString() ?? "/reflex/SMD";

Links:

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-coalescing-operator
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operators

Method 3

If deploying on Azure (as of August 2017), it is useful to also check if the Session keys array is populated, e.g.:

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x