0

Ive been using the following code for the last week and its worked no problem, then for some reason this morning its throwing:

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

My code:

DataSet icanData = (DataSet)HttpContext.Current.Session["icanDataSession"];
if (!(icanData == null))
{
     return icanData;
}

The reason I'm using HttpContext.Current.Session is because its running in a class.

pb2q
  • 58,613
  • 19
  • 146
  • 147
andrew slaughter
  • 1,069
  • 5
  • 19
  • 34
  • Run this code in different thread? – cuongle Oct 12 '12 at 10:45
  • You will need to check `HttpContext.Current.Session == null`, not `HttpContext.Current == null`. If the session is null, that could point to other issues. – nick_w Oct 12 '12 at 10:57
  • ive stopped it erroring by adding the following "if (HttpContext.Current != null && HttpContext.Current.Session != null)" however I dont think its storing the dataset in a session any more – andrew slaughter Oct 12 '12 at 11:02
  • Which part of the page lifecycle are you doing this from? `Page_Load`? – nick_w Oct 12 '12 at 11:33
  • Can you review my answer? I think it covers what you ended up doing to solve the problem. – nick_w Oct 12 '12 at 12:53

4 Answers4

1

Looks like Session["icanDataSession"]; has been lost.

Where in your code does it get set? Maybe any sessions that were originally stored in IIS have been lost via an App Pool recycle.

Darren
  • 68,902
  • 24
  • 138
  • 144
0

Check session is null before cast session object to dataset

if(HttpContext.Current.Session["icanDataSession"]=!null)
{
  DataSet icanData = (DataSet)HttpContext.Current.Session["icanDataSession"];
  if (!(icanData == null))
   {
     return icanData;
   }
}
else 
{
return new Dataset();
}
Anant Dabhi
  • 10,864
  • 3
  • 31
  • 49
  • i havent really found a solution so i can't really accept any of the answers above – andrew slaughter Oct 12 '12 at 12:18
  • ive sorted it, it seems that if i create the instance of the dataset on the page as private it kills it. im sure your all shaking your heads now thinking "school boy" error but thanks for all your help – andrew slaughter Oct 12 '12 at 12:46
0

I think, if this code is being called by an aspx.cs, then it will work fine. But if this is called by any stateless service, then it will throw error as you reported. Better to check if(HttpContext.Current != null) first..

Anupam
  • 1
0

You stated you were calling public static DataSet IcanData() at the top of your ASPX file. Instead, call that method from your Page_Load event. At the point in time where you are accessing the session it won't be available.

Information on why the session can be null can be found in this question: What should I do if the current ASP.NET session is null?

Community
  • 1
  • 1
nick_w
  • 14,758
  • 3
  • 51
  • 71