Using Cache API
ASP.NET Core applications can use NCache for object caching by simply using NCache Cache API. Here we describe how to get started with NCache Cache API in an ASP.NET Core application. You can see Client-side API Programming for a complete list of NCache-provided distributed caching features.
Prerequisites to Use Cache API
- Install the following NuGet packages in your application based on your NCache edition:
- Enterprise: Alachisoft.NCache.SDK
- Professional: Alachisoft.NCache.Professional.SDK
- The cache must be running.
- The application must be connected to cache before performing the operation.
- For API details, refer to: CacheItem, Expiration, Insert.
- Make sure that the data being added is serializable.
- To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
- To handle any unseen exceptions, refer to the Troubleshooting section.
Using NCache for Object Caching in ASP.NET Core
You can connect to an instance of the NCache within the application using the GetCache API and proceed to perform operations on the objects stored in the cache.
Note
To utilize the NCache APIs, include the following namespace in your application: Alachisoft.NCache.Client.
The following code initializes a cache and tries to fetch an album with a given ID from the cache. If not found in the cache, it fetches the specified data from the database and inserts it into the cache with a Sliding Expiration of 10 minutes.
public async Task<IActionResult> Details(int id)
{
ICache _cache = CacheManager.GetCache(_appSettings.CacheName); // Connect to cache in NCache
var cacheKey = string.Format("album_{0}", id);
Album album = null;
if (_cache != null)
{
album = _cache.Get<Album>(cacheKey); // Fetch Album object
}
if (album == null)
{
album = await DbContext.Albums
.Where(a => a.AlbumId == id)
.Include(a => a.Artist)
.Include(a => a.Genre)
.FirstOrDefaultAsync();
if (album != null)
{
if (_appSettings.CacheDbResults && _cache != null)
{
var cacheItem = new CacheItem(album);
cacheItem.SlidingExpiration = TimeSpan.AddMinutes(10);
// Add CacheItem to cache
_cache.Insert(cacheKey, cacheItem);
}
}
}
return View(album);
}
See Also
Multi-Region ASP.NET Core Session Provider for NCache
Session Storage in ASP.NET Core
ASP.NET Core Response Caching