Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 276
Luke Avatar asked Oct 19 '12 10:10

Luke


People also ask

How do I check if a session variable exists?

You can check whether a variable has been set in a user's session using the function isset(), as you would a normal variable. Because the $_SESSION superglobal is only initialised once session_start() has been called, you need to call session_start() before using isset() on a session variable.

How do you check session is exist or not in JavaScript?

Generally you don't have access to session cookies from JavaScript. The simplest way is just to make an ajax request to the server to check if you have an authenticated session. Alternatively you can set a custom cookie with session info. Show activity on this post.


2 Answers

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";
}
like image 70
Adil Avatar answered Oct 22 '22 15:10

Adil


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://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-coalescing-operator https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operators

like image 29
Luke Avatar answered Oct 22 '22 14:10

Luke