You may already be aware that HTTP is a stateless protocol and that the web server does not remember the user's status in between requests if you have been creating web apps for a while. It is challenging to provide the consumer with a personalized experience because of this limitation. To preserve user-specific data across several requests, developers must employ a variety of strategies, including session management. I'll give a quick rundown of sessions and some of their drawbacks in this post. Next, I'll go over how managing sessions in medium-to large-scale enterprise systems can benefit greatly from a distributed, highly scalable cache like NCache. Additionally, I will demonstrate how to set up, install, and utilize NCache in your ASP.NET Core web apps.
Although session management seems like a very attractive and useful
feature to most developers, as they gain more experience, they realize
that there are several limitations to using traditional session
management techniques. Some of the limitations are mentioned below.
The limitations mentioned above often prompt developers to adopt more
high-performance and scalable solutions like NCache that can not only
solve all of the problems but can also provide many additional features
to cache session data for your applications.
NCache provides various APIs to add, update, or remove data to/from
cache. The data can be stored as a single item or as bulk data.
Developers also have the option to store data either synchronously or
asynchronously as per their application requirements. The data stored in
the cache can be a primitive data type such as int, double, bool,
object, etc. or it can be any custom serializable class object, e.g.
Product, Order, etc.
Advantages of using NCache for Session Management
Following are some of the benefits of using NCache as your ASP.NET Core Session State Provider.
- High Availability: NCache replicates sessions
across multiple cache nodes to ensure that the session data is always
available, even during server failures. NCache provides a self-healing
peer-to-peer clustering architecture that has no single point of
failure. This dynamic clustering also allows us to add or remove any
cache server from the cluster without stopping the cache or the
applications.
- Multi-Region Replication: NCache can also
replicate ASP.NET Core sessions across multiple regions (data centers)
to ensure that the sessions remain safe, even if a data center goes
offline.
- Distributed & Scalable: NCache stores session
data in a distributed cache that allows your sessions to scale across
multiple servers. This also eliminates the single-point-of-failure
issues.
- Improved Performance: It enhances the performance
of session retrieval by caching session data in memory, reducing the
load on databases or slower storage systems. NCache also uses its custom
serialization method called ‘Compact Serialization’ which is much
faster than the slow serialization method available in .NET.
- Session Failover and Persistence: In the event of
an application server failure, NCache automatically handles session
failover to make sure that the sessions are not lost. It also supports
persistent session storage, allowing session data to survive across
application restarts.
- Support for Large Sessions: NCache can handle large session objects, distributing them efficiently across cache nodes.
- Cross-Platform Compatibility: NCache offers flexibility for different development environments by supporting both ASP.NET and ASP.NET Core applications.
- Increased Web Farm Efficiency: In multi-server
environments, NCache eliminates the need for "sticky sessions" by
synchronizing the session state across all servers.
- Enhanced Security: With encryption and secure
communication between cache clients and servers, NCache ensures that
sensitive session data remains protected.
Installing and Configuring NCache in ASP.NET Core App
Before we learn how to use NCache, we need to make sure we have
installed and configured NCache on the development machine. There are
multiple versions of NCache available, and you can choose the specific
version as per your application requirements.
- NCache Open Source: A free, open-source, and
community-supported version of NCache that provides basic distributed
caching features for small to medium applications.
- NCache Professional: This is a paid version of
NCache and it is suitable for small to medium-sized business
applications. It provides additional features such as client cache and
better performance optimizations.
- NCache Enterprise: The most advanced version of
NCache that provides the most advanced caching features, including
disaster recovery, high availability, and performance monitoring, and
it's the best choice for large enterprise applications.
Note. NCache Professional and Enterprise versions are also available as SaaS in both Azure and AWS marketplaces.
The next thing we need to decide is how we want to install and use NCache. We can choose one of the following options.
- NCache Cache Server: We can download and install the NCache cache server from the NCache official download page to enjoy features like distributed caching, high availability, replication, and scalability.
- NCache Docker Image: We can spin up an NCache cache server in a Docker container if you want to avoid installing NCache directly on our system.
- NCache Client (In Memory Cache): We can skip
NCache cache server installation and directly use NCache-related Nuget
packages in our .NET projects to use in-memory cache for quick testing
and proof of concepts.
For this article, I have downloaded the Open Source version of
NCache. Let’s create a new ASP.NET MVC Project in Visual Studio 2022
using .NET 8 and run the following commands in the Package Manager
Console to install the Open Source version of NCache.
Package Manager Console
Next, we need to configure NCache, and we have two options.
- We can specify all configurations through code in the Program.cs file.
- We can specify all configurations in JSON format in the appsettings.json file.
Let’s use option one and configure NCache in the Program.cs file.
Program.cs
The above code snippet uses the AddNCacheDistributedCache method to
configure NCache. This method adds NCache as the default distributed
cache implementation of the IDistributedCache interface. The method
requires CacheName and some other optional configurations.
Next, we need to add the following code in our HomeController.
HomeController.cs
The above code injects the IDistributedCache instance into the
constructor of the controller and then uses the Get and Set methods to
add and retrieve data from the cache.
Using NCache for ASP.NET Core Session Management
To use NCache ASP.NET Core Session Provider for session management we
need to install the following Nuget package in our project.
Package Manager Console
Next, we need to initialize the NCache sessions service in the Program.cs file as follows.
Program.cs
The complete details of all session-related options are available in NCache docs.
Next, we need to configure the HTTP request pipeline by adding middleware using the UserNCacheSession method.
Program.cs
After configuring NCache as the default cache for ASP.NET Core
Sessions, you can perform all session-specific operations without
modifying any code, and all sessions will be stored in the distributed
NCache. You just need to make sure that if you are storing custom
objects in the session, then they are marked as serializable. You can do
this by adding the [Serializable] attribute to your custom object class
definition.
Let’s implement a small To Do list app that will display a To Do list
to the user and will allow the user to add a new To-Do item to the
list. We will then store the To Do list in the ASP.NET core session that
will use NCache behind the scenes.
First of all, create the following ToDo model class with a single Name property.
ToDo.cs
Next, implement the following Index action methods in the
HomeController that will fetch the list ToDo list from the session using
the GetObject method and display it on the page.
HomeController.cs
The razor view page of the above action method will iterate over the
ToDo items and will render the names of all ToDo items in a simple
table. It also has a Create New button that will redirect the user to
another page where the user can add a new ToDo Item.
Index.cshtml
If you will test your page at this point, you should see the following output in the browser.
Next, implement the following Create action methods in the
HomeController. The first method will render the Create page in the
browser using the HttpGet request. The second method will be called when
the user submits the Create page by providing a new ToDo item name.
HomeController.cs
The above Create method first fetches the ToDo ToDo list from the
session, and if it doesn’t find any list in the session, it creates a
new list. Next, it adds the ToDo item to the list, and finally, it puts
the list back in the session using the SetObject method.
Please note that the GetObject and SetObject methods used above are
not the built-in methods of ASP.NET Core. I implemented the following
extension methods to easily add or retrieve custom objects in or from
the session.
SessionExtensions.cs
Following is the Razor view page of the Create action method.
Index.cshtml
You can now run the application and try to click the “Create New”
button. You should see the page similar to the following screenshot.
Try to create some ToDo items using the above form, and all items will be added to the list and session.
Summary
NCache is an ideal solution for managing sessions in high-traffic or
distributed web applications. In this article, we learned how
application resilience and user experience can be enhanced using NCache
features like session replication, high availability, and fault
tolerance. We also learned how to install, configure, and use NCache for
simple data caching as well as session data caching.
ASP.NET Core 9.0 Hosting Recommendation
One of the most important things when choosing a good ASP.NET Core 9.0 hosting is the feature and reliability.
HostForLIFE
is the leading provider of Windows hosting and affordable ASP.NET Core, their
servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent
and the features of the web hosting plan are even greater than what many
hosting providers ask you to pay for.
At HostForLIFE.eu, customers can also experience fast ASP.NET Core
hosting. The company invested a lot of money to ensure the best and fastest
performance of the datacenters, servers, network and other facilities. Its
datacenters are equipped with the top equipments like cooling system, fire
detection, high speed Internet connection, and so on. That is why
HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do
regular maintenance and monitoring works to assure its Orchard hosting are
security and always up.