Friday, April 13, 2012

HttpContext.Items

Each time client sends a HTTP request to ASP.NET web site or Web Service object of class HttpContext is created. This class many useful objects like Request, Response , Session , Application etc. HttpContext has one more collection named Items. In this article let us see what is use of this collection.

HttpContext.Items is IDictionary (Key value collection) like Session , Application but has life of only single HTTP request.  That means that when processing of server is finished and response is sent back to the client collection Items will be cleared. How to use HttpContext.Items

Add the value to Items collection
 
   HttpContext.Items["SomeKey"] = "SomeValue";

Retrieve the value from the Items collection


   if(HttpContext.Items["SomeKey"] != null)
          {
                   string value =  Convert.ToString(HttpContext.Items["SomeKey"]);
          }



Use of HttpContext.Items

  • Sharing data between the HttpModules/ HttpHandlers
 HttpContext.Items has life time of only single request; So it is used to pass (share and organize ) data between the HttpModule  and HttpHandler. Each request from client to server pass through different Http Modules and Http Handlers . So if we have written some custom Http Handlers or Http Modules and if you want to set some value in those modules or handlers and use it on web application specific to that request only then you can use HttpContext.Items collection

  •  Per request cache
 HttpContext.Items can be used for per request caching; This means that if your web page shows same information on the page multiple times like shopping cart at top and bottom of the page. or related information at different places on the same web page. In these case information can be brought from the database only once and kept at HttpContext.Items and use at whenever required.

No comments: