ResponseCache is a lightweight library that is used to cache API responses by simply putting ResponseCache attribute to the endpoint you want to cache.
Install-Package ResponseCache
services.AddMemoryCache();
services.AddInMemoryResponseCache();
First we bind cache settings with configuration values from appsettings.json then we add the service
var cacheSettings = new CacheSettings();
Configuration.GetSection(nameof(CacheSettings)).Bind(cacheSettings);
services.AddSingleton(cacheSettings);
services.AddSingleton<IConnectionMultiplexer>(_ => ConnectionMultiplexer.Connect(cacheSettings.ConnectionString));
services.AddDistributedRedisCache(options => options.Configuration = cacheSettings.ConnectionString);
services.AddDistributedResponseCache();
Add this to appsettings.json
"CacheSettings": {
"ConnectionString": "localhost:6379"
},
[ResponseCache(TTL)]
attribute where TTL
is an integer representing cache living time in seconds.
e.g. Cache response list of products for 1 minute
[ApiController]
[Route("[controller]")]
public class ProductsController : ControllerBase
{
private readonly DbContext _context;
public ProductsController(DbContext context)
{
_context = context;
}
[HttpGet]
[ResponseCache(60)]
public async Task<IActionResult> List()
{
return Ok(await _context.Products.ToListAsync());
}
}