Skip to main content

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 application 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 such sort of data.

Ways of managing Application State?
Now question is, which state storage provider is to be used and when? It is influenced by 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 change in HTTPContext object. Hence I’ll emphasis on that.

Items collection of HTTPContext is used to store data which is required only for that particular request. It means 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 another words, one middleware component can add data to HTTPContext.Items collection and other middleware component in the same HTTP request pipeline can read it. 
Why 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 to 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 access 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.