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!
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.
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.
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";
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With