NCache integrates seemingly with the ASP.NET Core framework. With NCache, we can cache application data or responses in our ASP.NET Core applications. Let’s take a look at another NCache feature for ASP.NET Core applications: Session State Caching with ASP.NET Core.
HTTP and Session State
A bit of background first. HTTP is a stateless protocol. It means requests are independent of each other, and servers don’t hold user data from previous requests. But, if we need to store user data while our users navigate through our web applications, we need to somehow keep user values between requests.
ASP.NET Core official documentation describes several approaches for state management. Like cookies, hidden fields, and query strings, among others.
To persist user data between requests, ASP.NET Core relies on a cookie and a server-side storage mechanism. On every request, ASP.NET Core passes a cookie with an identifier to fetch session data on the server side. By default, ASP.NET Core uses in-memory storage for session data.
But using in-memory storage for session data has some drawbacks. In case our application server goes offline, we lose our session data. If we reroute our traffic, we don’t get the session data replicated in the new location. And, If we have a server farm, we need to tie sessions to specific application instances, making our application hard to scale.
NCache for HTTP Session State Caching
We can use NCache for session state caching.
With NCache, we store our session data on a different process, in a cluster, to be precise. This way, we’re not limited by the amount of memory on our application server. And we can scale our cache cluster by adding more servers to it, increasing our transaction and storage capacity.
Thanks to NCache caching topologies and session replication, if our application server goes offline, we still have our session data available at all server nodes.
With NCache, we can replicate our session data across other regions or data centers. We always have session data available in case of disaster recovery, for example. Even we can keep session data at the location of its creation and move session data only when we move traffic between regions, keeping bandwidth consumption costs low.
For more benefits of using NCache for session state, check ASP.NET Core Caching Benefits and Overview.
We only need a few code changes to use NCache for session state caching. We have two approaches: use NCache as Session Provider or IDistributedCache
Provider.
Before using NCache as a Session provider, we need the AspNetCore.Session.NCache
NuGet package and add the Alachisoft.NCache.Web.SessionState
namespace.
Let’s add NCache as a Session provider to a sample .NET 6.0 ASP.NET Core web application. Like this,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
using Alachisoft.NCache.Web.SessionState; var builder = WebApplication.CreateBuilder(args); builder.Services.AddRazorPages(); builder.Services.AddControllersWithViews(); // 1. Add NCache as a Session Provider builder.Services.AddNCacheSession(config => { config.CacheName = "demoClusteredCache"; // To log all error information. (Optional) config.EnableLogs = true; // An identifier to make SessionId unique between applications. (Optional) config.SessionAppId = "demoApp"; }); // Alternatively, read settings from the appsettings.json file // //var ncacheSettingsSection = builder.Configuration.GetSection("NCacheSettings"); //builder.Services.AddNCacheSession(ncacheSettingsSection); var app = builder.Build(); if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error"); } app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); // 2. Store NCache session data app.UseNCacheSession(); app.MapRazorPages(); app.MapDefaultControllerRoute(); app.Run(); |
First, we add NCache services for Session State caching to the ASP.NET Core dependencies container. For that, we use the AddNCacheSession()
method. It expects an NCacheSessionConfiguration
object. We need to pass as a required parameter a cache name. Optionally we can enable logs (EnableLogs = true
) and pass an application identifier to make session ID unique between the applications using the same session data (SessionAppId = "demoApp"
).
Instead of manually configuring these parameters, we can use the appsettings.json
file and pass a configuration section to the AddNCacheSession()
method.
This is the appsettings.json
file for the settings from our previous example,
1 2 3 4 5 6 7 8 |
{ "NCacheSettings": { "CacheName": "demoClusteredCache", "EnableLogs": "true", "SessionAppId": "demoApp" }, // Other settings here... } |
For more details on the settings NCache has for its Session Provider, check ASP.NET Core Session Provider Configuration.
Once we register NCache services, we need to configure the HTTP request pipeline. We need to add the UseNCacheSession()
method. Let’s keep an eye on the order of our middleware in the request pipeline. We should add the NCache session middleware before any other middleware that reads session data.
Additionally, after adding NCache services and middleware, we access our session data using the Http.Session
class inside Razor pages and MVC Controllers.
2. NCache IDistributedCache implementation for Sessions
Instead of using the AddNCacheSession()
and UseNCacheSession()
methods to register NCache as a Session Provider, we can use ASP.NET Core sessions with NCache IDistributedCache implementation.
By default, ASP.NET Core has the AddDistributedMemoryCache()
method to register an in-memory implementation of the IDistributedCache
.
Instead of using that implementation, let’s add the NCache implementation using the AddNCacheDistributedCache()
method.
This time, we install the NCache.Microsoft.Extensions.Caching
NuGet package and use the Alachisoft.NCache.Caching.Distributed
namespace. Let’s change our previous sample Web application to use NCache IDistributedCache
implementation,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
using Alachisoft.NCache.Caching.Distributed; var builder = WebApplication.CreateBuilder(args); builder.Services.AddRazorPages(); builder.Services.AddControllersWithViews(); // 1. Add NCache Distributed Cache implementation builder.Services.AddNCacheDistributedCache(config => { config.CacheName = "demoClusteredCache"; // To log all error information. (Optional) config.EnableLogs = true; }); // 2. Add ASP.NET Core Session services builder.Services.AddSession(); var app = builder.Build(); if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error"); } app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); // 3. Add ASP.NET Core Session middleware app.UseSession(); app.MapRazorPages(); app.MapDefaultControllerRoute(); app.Run(); |
Notice, instead of registering the NCache services and middleware for Session State caching, we use ASP.NET Core AddSession()
and UseSession()
methods. But, we specify a different distributed cache implementation. The one from NCache.
To use the AddNCacheDistributedCache()
method, we need to pass the cache name as a required parameter. Again, we can use the appsetttings.json
file instead. Optionally, we can enable logs and exceptions and change request timeout and retry attempts. For all available configuration options for IDistributedCache
implementation, check Configure ASP.NET Core IDistributedCache.
After these steps, we can access our session data using the Http.Session
.
Conclusion
That’s how we can scale our ASP.NET Core applications using Session State Caching with NCache. Consequently, with only with a few code changes and configurations in our applications.
NCache has more features for state management. For example, NCache works like a Multi-Region ASP.NET Core Session Provider. Moreover, in case of disaster recovery or traffic rerouting, we can replicate our session data to avoid losing our session data.
Additionally, for those applications with legacy codebases still using ASP.NET Framework alongside the new ASP.NET Core, we can configure NCache to share sessions between the two frameworks.
So, take a closer look at NCache for Session Caching by checking NCache GitHub official repo for a sample application using Session caching to build a guessing game.