1

I have written following code in my global.asax file

void Application_PreRequestHandlerExecute(object sender, EventArgs e)
    {        
        ConnStr = objConnStr.GetConnectionString();


        if (HttpContext.Current.Session["LOGIN"] != null  )

        {   
 }
}  

It is throwing following error at *HttpContext.Current.Session["LOGIN"] *

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

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

what may be the issue ?

Manoj Patil
  • 19
  • 2
  • 3
  • 2
    Session can be null in several cases: http://stackoverflow.com/questions/1382791/asp-net-what-to-do-if-current-session-is-null – Alex Kamburov Mar 15 '12 at 14:54
  • Welcome to Stack Overflow! Please keep in mind that appreciation is shown through upvotes and accepted answers (checkmarks). If you have any questions, the [FAQ] is extremely useful, especially the [FAQ#HowToAsk] How to ask. – Justin Pihony Mar 16 '12 at 05:32

1 Answers1

5

This is most likely because HttpContext.Current.Session is null. You need to do this:

if (HttpContext.Current.Session != null 
    && HttpContext.Current.Session["LOGIN"] != null)

Now, HttpContext.Current could be null, also. However, in almost all practical cases (especially in asp) you can make a fair assumption that it will not be null. In fact, my current version of ReSharper does not even yell about Current possibly being null. So, that is more of a side note :) Your problem is most likely from Session

Justin Pihony
  • 66,056
  • 18
  • 147
  • 180
  • 1
    Is `HttpContext.Current` guaranteed not to be null? – phoog Mar 15 '12 at 14:48
  • You know, I kept waffling on that one. I believe it is extremely rare that it is null, but I cannot find anything guaranteeing it. In fact, the best I can find is this article about it being null: http://odetocode.com/articles/112.aspx I will re-update my answer – Justin Pihony Mar 15 '12 at 14:53
  • I've played around with code contracts a bit, and I've found several points in the framework where decompiling methods shows that there's no way they could return null, but yet there's no documentation of that fact (let alone a contract annotation). I wouldn't be surprised if this is one of them, but I don't have a decompiler handy on this computer to check. – phoog Mar 15 '12 at 14:59
  • Well, it probably depends on the usage, too. Like I mentioned, in ASP, I have NEVER heard of this being null... – Justin Pihony Mar 15 '12 at 15:01