Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.NullReferenceException When checking if != null

I'm using an ASHX handler, i want the handler to check if Session != null.

if (context.Session["Username"] != null)

And i get this error pointing this line:

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

What's the problem?

like image 790
Danpe Avatar asked Dec 05 '22 22:12

Danpe


2 Answers

if (context.Session["Username"] != null)

Does your handler implement IRequiresSessionState? Otherwise Session might not be available.

From MSDN:

Specifies that the target HTTP handler requires read and write access to session-state values. This is a marker interface and has no methods.

like image 85
BrokenGlass Avatar answered Dec 07 '22 11:12

BrokenGlass


Use it like this. One of the encapsulating objects may be already null:

if (context != null)
  if (context.Session != null)
    if (context.Session["Username"] != null) {
      // Do stuff
}
like image 25
Teoman Soygul Avatar answered Dec 07 '22 11:12

Teoman Soygul