Application State in ASP.NET Core 1.0

Introduction to Application State

Application state provides a way to store in-memory data, which are smaller in size. It includes both global and user-specific data. Such data can be used across applications and can be used by all users. Prior to ASP.NET Core 1.0 also there were application and session state options available to store this type of data.

Ways of managing application state?

Now the question is, which state storage provider is to be used and when? It is influenced by a variety of factors:
  • Size of data
  • Format of data
  • Duration to persist data
  • Sensitivity of data, etc.
Based on your answers, application state can be managed in variety of ways like:
  • HTTPContext
  • Cookies
  • Session
  • Querystring and Post
  • Cache
  • Other options (EF, Azure Table Storage, etc.)
As part of ASP.NET Core 1.0 release, there is a change in HTTPContext object. Hence I’ll expand on that.

HTTPContext:

Items collection of HTTPContext is used to store data which is required only for that particular request. It meansthe contents are discarded and renewed after every HTTP request. HTTPContext.Items is a simple dictionary collection of type IDictionary<object, object>. HTTPContext.Items is very useful in sharing data between various middleware components. In other words, one middleware component can add data to HTTPContext.Items collection and another middleware component in the same HTTP request pipeline can read it. Ways to get an instance of HTTPContext can be found here.

Why is HTTPContext re-introduced?

Main reasons for re-introducing HTTPContext are:
  • ASP.NET Core 1.0 no more uses System.Web assembly. It was done in order to reduce the application footprint by introducing new libraries based on functionality.

  • Huge size of object graph for HttpContext. Earlier this size was approximate 30K, which has now come down to approximate 2K.
Application State Considerations
  • Data is stored in-memory. Hence it is fast as compared toa  database stored on the server.
  • Application state stores data as Object type, so value has to be converted to appropriate type while reading.
  • Application state data can be accessed simultaneously by many threads. So, data updates should be done in thread-safe manner.
  • Application state cannot be preserved in Web Farm and Garden scenarios.
Ebook Download
View all
Learn
View all