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 specific operations without any code change. All sessions will be cached in distributed NCache.
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 Sliding Expiration of the cache entry to 30 minutes.
For more deatil on IDistributedCache
methods, have a look at their documentation.
In 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 retobj = _cache.Get(cacheKey);
// Check if key exists in cache
if (retobj != 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 at:
Shipped with NCache: %NCHOME%\samples\dotnetcore\SessionCaching
See Also
Configure ASP.NET Core Sessions with NCache IDistributedCache Provider
Multi-Region ASP.NET Core Session Provider for NCache
Object Caching in ASP.NET Core
ASP.NET Core Response Caching