开发者

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开发者_如何学C this error pointing this line:

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

What's the problem?


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.


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
}


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜