ASP.NET Core Sessions Usage
NCache provides integration with ASP.NET Core Sessions through the implementation of the common IDistributedCache interface. Using NCache as a distributed session store is possible without any changes to existing code. Storing the session state in a distributed NCache cluster ensures that sessions are persisted, scalable, and highly available in a web farm.
For more details on IDistributedCache methods, have a look at their documentation.
Prerequisites
Before using the ASP.NET Core Sessions with NCache, ensure that the following prerequisites are fulfilled:
- Install the following NuGet packages in your application based on your NCache edition:
- Enterprise: AspNetCore.Session.NCache
- OpenSource: AspNetCore.Session.NCache.Opensource
- To utilize the extension, include the following namespaces in your application:
- The cache must be running.
- For API details, refer to: AddNCacheSession, UseNCacheSession.
- Make sure that the data being added is serializable.
Using ASP.NET Core Sessions for a Single Cache
The following code sample looks for the cache key, if it is found, it returns the view with the result. If not, it adds the cache key with its corresponding cache entry and sets the Sliding Expiration of the cache entry to 30 minutes. To use ASP.NET Core Sessions, update HomeController.cs of your application as follows:
// Constructor injection for the IDistributedCache interface
public class HomeController : Controller
{
private IDistributedCache _cache;
public HomeController(IDistributedCache Cache)
{
// NCache is the underlying distributed provider
_cache = Cache;
}
public IActionResult CacheOperations()
{
try
{
DateTime cacheEntry;
string cacheKey = "MaxValue: " + DateTime.MaxValue;
object retrieveObj = _cache.Get(cacheKey);
if (retrieveObj != null)
{
// Return view with result
return View();
}
else
{
cacheEntry = DateTime.MaxValue;
var cacheEntryOptions = new DistributedCacheEntryOptions
{
SlidingExpiration = TimeSpan.FromMinutes(30)
};
_cache.Set(cacheKey, new byte[1024], cacheEntryOptions);
return View(cacheEntry);
}
}
catch (Exception ex)
{
// Handle error (log, fallback, etc.)
// Example: return fallback view or error page
return StatusCode(500, $"Cache error: {ex.Message}");
}
}
}
Note
To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
Using ASP.NET Core Sessions For Multiple Caches
To utilize multiple caches with ASP.NET Core Sessions, modify your HomeController.cs to use IDistributedCacheFactory, enabling dynamic cache selection for session management based on specific cache configurations.
public class HomeController : Controller
{
private IDistributedCacheFactory _cache;
public HomeController(IDistributedCacheFactory cacheFactory)
{
// Underlying cache is NCache
_cache = cacheFactory.GetDistributedCache("demoClusteredCache");
}
public IActionResult CacheOperations()
{
try
{
DateTime cacheEntry;
string cacheKey = "MaxValue: " + DateTime.MaxValue;
object retrieveObj = _cache.Get(cacheKey);
if (retrieveObj != null)
{
// Return view with result
return View();
}
else
{
cacheEntry = DateTime.MaxValue;
var cacheEntryOptions = new DistributedCacheEntryOptions
{
SlidingExpiration = TimeSpan.FromMinutes(30)
};
_cache.Set(cacheKey, new byte[1024], cacheEntryOptions);
return View(cacheEntry);
}
}
catch (Exception ex)
{
// Log error here if needed
return StatusCode(500, $"Cache error: {ex.Message}");
}
}
}
Additional Resources
NCache provides a sample application for session caching on GitHub.
See Also
.NET: Alachisoft.NCache.Caching.Distributed namespace.