Hi,
Why is the MemoryCache's Get method is always null?
using Microsoft.Extensions.Caching.Memory; //PM> CacheManager.Microsoft.Extensions.Caching.Memory -Version 1.1.0
public class IndexController
{
IMemoryCache _memoryCache;
public IndexController(IMemoryCache memoryCache)
{
_memoryCache = memoryCache;
}
public IActionResult Index(string key)
{
object isCached = _memoryCache.Get(key); //<<--always null on every request
if (isCached != null){
//cache item
object cacheEntry;
string data = "string-data-here";
// Look for cache key.
if (!_memoryCache.TryGetValue(key, out cacheEntry))
{
// Key not in cache, so get data.
cacheEntry = data;
// Set cache options.
var cacheEntryOptions = new MemoryCacheEntryOptions()
// Keep in cache for this time, reset time if accessed.
.SetSlidingExpiration(TimeSpan.FromMinutes(60));
// Save data in cache.
_memoryCache.Set(key, cacheEntry, cacheEntryOptions);
}
}
}
Thanks,