HttpContext.Items[] vs Session[]

Since .NET first because available, passing data around during a request has become a lot easier.  The ability to set a property has made that so.  Still there are times when setting a property just won’t do the trick.

One such time is getting data from the middle tier back up to the view separate from a DataBinding operation.  That is, you databind a control to the middle tier and that method needs to set a value that will be used elsewhere in the view.  Not in the item that is being bound.

The natural, obvious, tendency is to set a session variable.  But, there is a better way.

The problem with session variables is that they have to be cleaned up manually or they will hang around longer than we actually need them.  This will use up more session memory than is required and can potentially cause side effects that will be difficult to debug.

Instead you can use the Items[] collection that is part of the HttpContext class.  It works the same as a session variable, but it only hangs around for the duration of the request.  Once the information is sent back to the browser, the variables that were set in the Items[] collection go away.

You might set your variable in the middle tier like this:

HttpContext.Current.Items["myVar"] = "Some Data Here";

And retrieve it later like this:

string myVar = (string)(HttpContext.Current.Items["myVar"]);

 

References
0

Dave Bush has been programming for 20 years. He currently blogs about .NET at http://blog.dmbcllc.com and provides .NET coaching to small and medium sized companies. Dave is a DZone MVB and is not an employee of DZone and has posted 20 posts at DZone.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

jbubriski replied on Tue, 2009/10/13 - 1:01pm

Hey David,

   Good article to point out the difference between Session and the HttpContext.Items[] property.  Rick Strahl has a great article about how he stores the Data Context for LINQ (or EF) in the HttpContext, so there is only one context per request, but you don't have to handle the instantiation and disposal of multiple contexts.  I personally use this method in many of my projects, and have not had any issues with it.

   However, as a side note, I would be weary of what you put into these dictionaries, mainly for performance.  Even though the HttpContext.Items[] is probably a much better choice than the Session state, long lived requests would still hold references, and could be potentially harmful to your performance if you use the collection without regard.

-John

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.