Shame and Down to Earth HttpContext.Items Property

There is a few options to used if you want to stored object on the server-side. Some of the common techniques people used are including Session, Cache, Application. There's a different between each of the techniques.Obviously Items does not gain a lot of attention from developer. Mike Duncan has posted 3 hot uses for HttpContext.Current.Items that might change the way developers look at it. So what it is? What so special about it? Where can I used it? Taken from MSDN site:

Gets a key/value collection that can be used to organize and share data between an IHttpModule interface and an IHttpHandler interface during an HTTP request.

Notice the word HTTP request. It can be used to stored object in a single HTTP request to achieve a singleton in ASP.NET (only in single request). Ah ha. Simple idea how we can take advantage of this is by creating a class that can be used to stored key and object in a single HTTP request. This idea can be expand to create a more reusable framework for managing context. Another advantage of this property is that you can add object in all http request pipeline. Meaning you can share data between httpmodules and httphandlers implementation. One example use of HttpContext.Items is to store page setting when visitor request for the page.

   1: public static PageSettings GetPageSetting()
   2: {
   3:     if (HttpContext.Current == null) return null;
   4:  
   5:     PageSettings currentPage = HttpContext.Current.Items["CurrentPage"] as PageSettings;
   6:     if (currentPage == null)
   7:     {
   8:         currentPage = LoadCurrentPage();
   9:         if (currentPage != null)
  10:             HttpContext.Current.Items["CurrentPage"] = currentPage;
  11:     }
  12:     return currentPage;
  13: }

There's lack of documentation about HttpContext.Items from Microsoft. Here's are some of the resources I found:

Until next time.

2 Comments

Comments have been disabled for this content.