System.NullReferenceException When checking if != null

馋奶兔 提交于 2019-12-10 18:03:19

问题


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?


回答1:


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.




回答2:


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:


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




回答4:


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



来源:https://stackoverflow.com/questions/5774248/system-nullreferenceexception-when-checking-if-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!