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?

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh stupid me, I should have add IReadOnlySessionState... I found this link: hanselman.com/blog/…
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
}

3 Comments

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

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.