Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
.NET Core Web API - Showing usage of Distributed Memory Cache
// Startup.cs to configure distributed memory cache.
public class Startup
public void ConfigureServices(IServiceCollection services)
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
// Some code...
// WeatherForecastController.cs - Showing usage of cache
public class WeatherForecastController : ControllerBase
private static readonly string[] Summaries = new[]
"Freezing", "Bracing", "Chilly", "Cool",
"Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
private readonly ILogger<WeatherForecastController> _logger;
private readonly IDistributedCache _distributedCache;
private readonly string WeatherForecastKey = "WeatherForecast";
public WeatherForecastController(ILogger<WeatherForecastController> logger, IDistributedCache distributedCache)
_logger = logger;
_distributedCache = distributedCache;
public async Task<IEnumerable<WeatherForecast>> Get()
// Find cached item
byte[] objectFromCache = await _distributedCache.GetAsync(WeatherForecastKey);
if (objectFromCache != null)
// Deserialize it
var jsonToDeserialize = System.Text.Encoding.UTF8.GetString(objectFromCache);
var cachedResult = JsonSerializer.Deserialize<IEnumerable<WeatherForecast>>(jsonToDeserialize);
if (cachedResult != null)
// If found, then return it
return cachedResult;
// If not found, then recalculate response
var result = GenerateResponse();
// Serialize the response
byte[] objectToCache = JsonSerializer.SerializeToUtf8Bytes(result);
var cacheEntryOptions = new DistributedCacheEntryOptions()
// Cache it
await _distributedCache.SetAsync(WeatherForecastKey, objectToCache, cacheEntryOptions);
return result;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment