- ASP.NET Core MVC
- ASP.NET Core logging with Serilog
- ASP.NET Core managed config
- ASP.NET Core MVC with /api/-area
- ASP.NET Core API versioning
- ASP.NET Core API with Swagger UI
- ASP.NET Core EF in separate project
- ASP.NET Core AutoMapper
- ASP.NET Core response cache
- ASP.NET Core memory cache
- ASP.NET Core TypeScript
Response cache is fine for simpler operations, but sometimes you need more fine grained control. System.Runtime.Caching.MemoryCache has builtin support for in-memory cache with expiry.
Install
Install-Package System.Runtime.Caching
Implement
To register as a service add this to Startup.cs ConfigureServices:
services.AddMemoryCache();
Use
public class HomeController : Controller
{
private readonly IMemoryCache _cache;
public HomeController(IMemoryCache memoryCache)
{
_cache = memoryCache;
}
[HttpGet]
public string CurrentTime()
{
var cacheEntry = _cache.GetOrCreate("CurrentTime", entry =>
{
entry.SlidingExpiration = TimeSpan.FromSeconds(10);
return DateTime.Now.ToString();
});
return cacheEntry;
}
}
A colleague requested a more complex scenario where we need the cache to update exactly every 1 minute, since numbers from all requests to that particular API should be approximately in sync.
[HttpGet]
public string CurrentTime()
{
var cacheEntry = _cache.GetOrCreate("CurrentTime", entry =>
{
// Calculate next whole minute
var now = DateTimeOffset.Now.ToUnixTimeSeconds();
var expires = now + 60 - (now % 60);
entry.AbsoluteExpiration = DateTimeOffset.FromUnixTimeSeconds(expires);
return DateTime.Now.ToString();
});
return cacheEntry;
}