You can use ASP.NET cache which is available in Microsoft.Extensions.Caching.Memory Nuget Package.
Install this package if it is not available.
Then you need to register the cache memory service:
public void ConfigureServices(IServiceCollection services)
{
services.AddMemoryCache();
}
Consume your cache service into a controller:
public class CacheController : Controller
{
private readonly IMemoryCache _cache;
public TokenController(IMemoryCache cache)
{
_config = config;
}
}
Use the below function to get or set cache data:
public T GetOrSet<T>(string cacheKey, Func<T> getItemCallBack)
{
var item = _cache.Get<T>(cacheKey);
if (item == null)
{
item = getItemCallBack();
_cache.Set(cacheKey, item, CacheKeysWithOption.CacheOption);
}
return item;
}
And consume GetOrSet:
public IActionResult CacheTryGetValueSet()
{
var list = GetOrSet(CacheKeysWithOption.Entry, GetStringList);
return new JsonResult(list);
}
[NonAction]
public List<String> GetStringList()
{
List<String> str = new List<string>()
{
"aaaaa",
"sssdasdas",
"dasdasdas"
};
return str;
}