ASP.NET Core Session Storage Strategies

Since the HTTP protocol used by web applications is a stateless protocol, data is not stored anywhere; for every web request, a new HTTP connection is opened by the browser. For catering situations in which saving your data is crucial, ASP.NET Core provides sessions for storing user data. This data store is maintained by the ASP.NET Core application itself on the same server as the application. 

Although ASP.NET Core provides an in-memory session provider that stores sessions, sometimes the load needs to be balanced. In these scenarios, session storage strategies, like sticky sessions or distributed cache, come into use.

Sticky Sessions a Big No, Why?

When using sticky sessions, a load balancer is used, and all the user requests are directed to a single server. The main disadvantage of using sticky sessions for your ASP.NET Core application is the improper distribution of load. Sometimes the requests increase to such a level that they completely overload the server responsible for maintaining data. Also, if this server goes down, data may be completely lost, causing a single point of failure.

Storing ASP.NET Core Sessions in Distributed Cache

Distributed cache resolves all the issues faced when using sticky sessions. A distributed cache is a cache store used by multiple application servers, typically maintained as an external service for keeping and accessing data. The major advantage of a distributed cache is that it not only increases scalability but also increases the performance of an ASP.NET Core Application. The diagram below shows how a distributed cache serves its purpose for storing sessions. Multiple servers can be added in the distributed cache cluster, making it linearly scalable. Users communicate with the ASP.NET Core web farm through a load balancer. The web farm further uses a distributed cache for storing sessions services provider.

Storing sessions in distributed cache

Storing sessions in distributed cache

ASP.NET Core’s Default IDistributedCache Interface

IDistributedCache interface is provided by Microsoft for integrating a distributed cache in ASP.NET Core applications. The application interacts with the cache using this interface regardless of the cache implementation being used. Here is how you can configure your session store provider through IDistributedCache.

C#
 




xxxxxxxxxx
1
13


 
1
namespace Microsoft.Extensions.Caching.Distributed
2
{
3
    public interface IDistributedCache
4
    {
5
       // Each of these methods also has an “Async” overload
6
        byte[] Get(string key);
7
        void Refresh(string key);
8
        void Remove(string key);
9
       // Specify absolute & sliding expiration thru options
10
        void Set(string key, byte[] value,
11
                DistributedCacheEntryOptions options);
12
    }
13
}



Note: All of these methods have an async overload as well.

Using the IDistributedCache

Here is a small example to help you understand how to use the IDistributed cache.

C#
 




xxxxxxxxxx
1
15


 
1
IDistributedCache _cache;
2
...
3
private byte[] LoadCustomer(string custId) {
4
    string key = "Customers:CustomerID:"+ custId;
5
    // is the customer in the cache?
6
    byte[] customer = _cache.Get(key);
7
    if(customer == null) 
8
    {
9
       // the cache doesn't have it. so load from DB
10
       customer = LoadFromDB(key);
11
       // And, cache it for next time
12
       _cache.Set(key, customer);
13
    }
14
    return customer;
15
}



IDistributedCache Interface Limitations

There are certain limitations when using the IDistributedCache interface. ASP.NET Core session implementation omitted a few features that were previously supported in ASP.NET Core Session State. These include:

  1. Session Locking.
  2. Byte [] for Custom Objects.

Apart from these, if you implement the IDistributedCache interface for your ASP.NET Core application, you would not have various cache features that you get by using an implementation provided by a distributed cache solution such as NCache.

ASP.NET Core Session Provider for Distributed Cache

Distributed cache, such as NCache, provides an easy to use implementation for session storage. This not only saves your time in writing your own provider but also gives you access to various distributed cache features. Distributed cache (NCache) also tackles limitations of IDistributedCache mentioned above. It provides an internal session locking mechanism and also supports custom objects.

Configuring Session Provider for Distributed Cache

For configuration of the session provider for distributed cache, there is less programming effort required. Distributed cache, such as NCache, allows you to configure its provider by either configuring all settings in Startup.cs class or by reading them through theAppSettings.json file in your ASP.NET Core application.

The following example shows how to configure a distributed cache (NCache) provider in the Startup.cs class of your ASP.NET Core application:

C#
 




xxxxxxxxxx
1
11


 
1
public void ConfigureServices(IServiceCollection services)
2
{
3
   . . .
4
 
          
5
    services.AddNCacheDistributedCache(configuration =>
6
    {
7
        configuration.CacheName = "myDistributedCache";
8
        configuration.EnableLogs = true;
9
        configuration.ExceptionsEnabled = true; 
10
    });
11
}



Using Distributed Cache With ASP.NET Core Sessions

After successful configuration of distributed cache (NCache) for storing sessions, you can easily use it in your ASP.NET Core application for Read and Write operations. The following block of code represents how to fetch an item from the cache and how to insert an item in it.

C#
 




xxxxxxxxxx
1
21


 
1
DateTime cacheEntry;
2
string key = "MaxValue: " + DateTime.MaxValue;
3
 
          
4
// Look for cache key
5
object retobj = _cache.Get(key);
6
 
          
7
// Check if key exists in cache
8
if (retobj == null)
9
{
10
    // Key not in cache, so populate data in cache entry
11
    cacheEntry = DateTime.MaxValue;
12
 
          
13
    // Configure SlidingExpiration for item 
14
    var cacheEntryOptions = new DistributedCacheEntryOptions();
15
    cacheEntryOptions.SlidingExpiration = TimeSpan.FromMinutes(30);
16
 
          
17
    // Insert item in cache
18
    _cache.Set(key, new byte[1024], cacheEntryOptions);
19
 
          
20
    // Return view with cacheEntry
21
}



Conclusion

For configuring NCache Session Provider for ASP.NET Core applications, very little coding is required. It is very easy to configure and you do not have to write very long code snippets. Apart from this, NCache provides other benefits including:

To sum it all up, NCache is not only fast but scalable. It is purely native .NET, which makes it very feasible for fitting in your .NET application stack.


Further Reading

 

 

 

 

Top