Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

ASP.NET Core Session Storage Strategies

DZone 's Guide to

ASP.NET Core Session Storage Strategies

Use distributed cache to overcome load distribution issues.

· Web Dev Zone ·
Free Resource

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


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.

namespace Microsoft.Extensions.Caching.Distributed
{
    public interface IDistributedCache
    {
       // Each of these methods also has an “Async” overload
        byte[] Get(string key);
        void Refresh(string key);
        void Remove(string key);
       // Specify absolute & sliding expiration thru options
        void Set(string key, byte[] value,
                DistributedCacheEntryOptions options);
    }
}


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.

IDistributedCache _cache;
...
private byte[] LoadCustomer(string custId) {
    string key = "Customers:CustomerID:"+ custId;
    // is the customer in the cache?
    byte[] customer = _cache.Get(key);
    if(customer == null) 
    {
       // the cache doesn't have it. so load from DB
       customer = LoadFromDB(key);
       // And, cache it for next time
       _cache.Set(key, customer);
    }
    return customer;
}


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 the AppSettings.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:

public void ConfigureServices(IServiceCollection services)
{
   . . .

    services.AddNCacheDistributedCache(configuration =>
    {
        configuration.CacheName = "myDistributedCache";
        configuration.EnableLogs = true;
        configuration.ExceptionsEnabled = true; 
    });
}


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.

DateTime cacheEntry;
string key = "MaxValue: " + DateTime.MaxValue;

// Look for cache key
object retobj = _cache.Get(key);

// Check if key exists in cache
if (retobj == null)
{
    // Key not in cache, so populate data in cache entry
    cacheEntry = DateTime.MaxValue;

    // Configure SlidingExpiration for item 
    var cacheEntryOptions = new DistributedCacheEntryOptions();
    cacheEntryOptions.SlidingExpiration = TimeSpan.FromMinutes(30);

    // Insert item in cache
    _cache.Set(key, new byte[1024], cacheEntryOptions);

    // Return view with cacheEntry
}


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:

  • High Availability.
  • Linearly Scalable.
  • Intelligent Session Replication.
  • Fast Dynamic Compact Serialization.

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.

Topics:
asp.net core session ,session storage ,distributed cache

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}