2

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?

Teoman Soygul
  • 25,584
  • 6
  • 69
  • 80
Danpe
  • 18,668
  • 21
  • 96
  • 131

4 Answers4

11
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.

BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
  • Oh stupid me, I should have add `IReadOnlySessionState`... I found this link: http://www.hanselman.com/blog/GettingSessionStateInHttpHandlersASHXFiles.aspx – Danpe Apr 25 '11 at 00:51
4

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
}
Teoman Soygul
  • 25,584
  • 6
  • 69
  • 80
  • 3
    It is always safer to stack null checks like the one above, so that you can pinpoint the exact source of the problem. Seems like a chore but pays off. – Teoman Soygul Apr 25 '11 at 00:54
  • 1
    this approach is reasonable if there is an alternate code path if Session is not available - on the other hand if it is a hard assumption to expect the Session to be there and your code *depends* on this assumption, the **fail fast** approach would be to just let it throw an exception, otherwise chances are you are masking this problem with a null check. – BrokenGlass Apr 25 '11 at 01:37
  • 1
    Well of course nested if statements should be complemented with nested else's, where it would be suitable to deal with a null object (which shouldn't be null in the first place) and throw a proper exception with a proper message. – Teoman Soygul Apr 25 '11 at 01:43
1

Yeah I'd say that check to see if the context is not null first.

John Batdorf
  • 2,502
  • 8
  • 35
  • 43
0

I had a similar problem with an .ashx file. The solution was that the handler has to implement IReadOnlySessionState (for read-only access) or IRequiresSessionState (for read-write access). eg:

public class myModule: IHttpHandler, IRequiresSessionState { ... }

These Interfaces do not need any additional code but act as markers for the framework.

Hope that this helps.

Jonathan

Jonathan Stanton
  • 2,531
  • 1
  • 28
  • 35