I have one ASP.Net MVC - 5 application and I want to check if the session value is null before accessing it. But I am not able to do so.
//Set
System.Web.HttpContext.Current.Session["TenantSessionId"] = user.SessionID;
// Access
int TenantSessionId = (int)System.Web.HttpContext.Current.Session["TenantSessionId"];
I tried many solutions from SO
Attempt
if (!string.IsNullOrEmpty(Session["TenantSessionId"] as string))
{
//The code
}
Kindly guide me.
Error: NULL Reference
As
[]
is act asIndexer
(like a method on the class) and in this case,session
isnull
and you cannot perform Indexing on it.Try this..
The NullReferenceException comes from trying to cast a null value. In general, you're usually better off using
as
instead of a direct cast:That will never raise an exception. The value of
tenantSessionId
will simply be null if the session variable is not set. If you have a default value, you can use the null coalesce operator to ensure there's always some value:Then, it will either be the value from the session or the default value, i.e. never null.
You can also just check if the session variable is null directly:
However, you would need to confine all your work with the session variable to be inside this conditional.