7

Próbuję ustalić, czy zmienna Session istnieje, ale dostaję błąd:nie może wykryć, czy istnieje zmienna Session

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

Kod:

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

to dlatego, nazwa Session "ścieżka_firmy" nie istnieje, ale nie mogę jej wykryć!

Odpowiedz

22

Nie używaj ToString(), jeśli chcesz sprawdzić, czy Session ["company_path"] ma wartość null. Jak if Session["company_path"] is null then Session["company_path"].ToString() will give you exception.

Zmień

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

Aby

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

Dzięki za odpowiedź, nadal otrzymuję ten sam błąd z tym – Luke

+0

Sprawdź, czy twój bieżący wątek może uzyskać dostęp do System.Web.HttpContext? – Adil

+1

Jak mogę to sprawdzić? Mam 'using System.Web'? Czy to jest poprawne? – Luke

0

przypadku wdrażania na Azure (od sierpnia 2017), warto również sprawdzić, czy tablica klucze sesja jest zaludniony , np .:

Session.Keys.Count > 0 && Session["company_path"]!= null 
Powiązane problemy