DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Enhance the Performance of .NET Core Applications for Large Responses
  • Deploy an ASP.NET Core Application in the IBM Cloud Code Engine
  • Implementing Cache Dependency in ASP.NET Core
  • GDPR Compliance With .NET: Securing Data the Right Way

Trending

  • Java's Quiet Revolution: Thriving in the Serverless Kubernetes Era
  • Building Scalable and Resilient Data Pipelines With Apache Airflow
  • Microsoft Azure Synapse Analytics: Scaling Hurdles and Limitations
  • Docker Model Runner: Streamlining AI Deployment for Developers
  1. DZone
  2. Data Engineering
  3. Data
  4. ASP.NET Core Session Storage Strategies

ASP.NET Core Session Storage Strategies

Use distributed cache to overcome load distribution issues.

By 
Iqbal Khan user avatar
Iqbal Khan
·
Updated Mar. 11, 20 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
24.0K Views

Join the DZone community and get the full member experience.

Join For Free

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:

  • 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.


Further Reading

  • NCache: Scaling .NET Core Applications for Extreme Performance.
  • Core .NET.
ASP.NET ASP.NET Core Session (web analytics) Distributed cache Cache (computing) application

Published at DZone with permission of Iqbal Khan. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How to Enhance the Performance of .NET Core Applications for Large Responses
  • Deploy an ASP.NET Core Application in the IBM Cloud Code Engine
  • Implementing Cache Dependency in ASP.NET Core
  • GDPR Compliance With .NET: Securing Data the Right Way

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!