ASP.NET Core Sessions Usage
Once you have configured NCache as the default cache for ASP.NET Core Sessions, you can perform all ASP.NET Core Sessions-specific operations without any code change. All sessions will be cached in distributed NCache.
For more detail on IDistributedCache
methods, have a look at their documentation.
Using ASP.NET Core Sessions For a Single Cache
The following code sample looks for the cache key in the cache, if it is found, it returns the view with the result. If not, it adds the cache key against 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:
public class HomeController : Controller
{
private IDistributedCache _cache;
public HomeController(IDistributedCache Cache)
{
// Underlying cache is NCache
_cache = Cache;
}
public IActionResult CacheOperations()
{
// Cache entry is of DateTime type
DateTime cacheEntry;
string cacheKey = "MaxValue: " + DateTime.MaxValue;
// Look for cache key
object retrieveObj = _cache.Get(cacheKey);
// Check if key exists in cache
if (retrieveObj != null)
{
// Return view with result
}
else
{
// 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(cacheKey, new byte[1024], cacheEntryOptions);
// Return view with cacheEntry
}
}
}
Using ASP.NET Core Sessions For Multiple Caches
To utilize multiple caches with ASP.NET Core Sessions, modify your HomeController.cs to use the IDistributedCacheFactory
, enabling dynamic cache selection for session management based on specific cache configurations.
Note
This feature is available in NCache Enterprise only.
public class HomeController : Controller
{
private IDistributedCacheFactory _cache;
public HomeController(IDistributedCacheFactory cacheFactory)
{
// Underlying cache is NCache
_cache = cacheFactory.GetDistributedCache("demoClusteredCache");
}
public IActionResult CacheOperations()
{
// Cache entry is of DateTime type
DateTime cacheEntry;
string cacheKey = "MaxValue: " + DateTime.MaxValue;
// Look for cache key
object retrieveObj = _cache.Get(cacheKey);
// Check if key exists in cache
if (retrieveObj != null)
{
// Return view with result
}
else
{
// 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(cacheKey, new byte[1024], cacheEntryOptions);
// Return view with cacheEntry
}
}
}
Additional Resources
NCache provides sample application for Session Caching on GitHub.
See Also
.NET: Alachisoft.NCache.Caching.Distributed namespace.