In our ASP.NET Web Application, we have a service with a life-time/scope that can described as "instance per request" i.e. the instance is stored in the HttpContext.Current.Items
collection.
We have had this intermittent issue where the HttpContext.Current
property is null
during calls from the ASP.NET ReportViewer
control. Sometimes it is null
, sometimes it is not. The behaviour can be different on the staging website versus a dev machine, and even varies between different dev machines.
This will cause a report which would like to use our service to throw an exception.
Why is the HttpContext.Current
property null
?
Why is it intermittent?
The source of the problem seems to be that the Report Viewer sometimes uses Thread Pool threads to retrieve data for DataSets defined in the report. Thread Pool threads cannot access the HttpContext.Current
instance of the thread servicing the HTTP request (more information in this blog post).
The reports in my scenario had a number of DataSets in the report definition which each corresponded to an ObjectDataSource
defined on the page. After extensive debugging I found that the report would retrieve the data for the first DataSet declared in the report definition on the same thread that services the HTTP request. Any subsequent DataSets would either be retrieved on the main HTTP request thread or a Thread Pool thread. These subsequent DataSets would then intermittently throw exceptions saying that HttpContext.Current
was null.
There does not seem to be any way to predict or control what thread a DataSet will be retrieved on after the first one.