In-Memory Cache is a feature in ASP.NET that allows you to temporarily store data in the server's memory. This reduces the need for repetitive database or API calls, improving performance.
Follow these steps to use in-memory caching in your application:
// Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMemoryCache(); // Register in-memory cache
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();
The AddMemoryCache
method enables in-memory caching in the application.
// Controllers/WeatherController.cs
[ApiController]
[Route("api/weather")]
public class WeatherController : ControllerBase
{
private readonly IMemoryCache _cache;
public WeatherController(IMemoryCache cache)
{
_cache = cache;
}
[HttpGet]
public IActionResult GetWeather()
{
const string cacheKey = "weatherData";
if (!_cache.TryGetValue(cacheKey, out string weather))
{
// Simulate fetching data (e.g., from an API)
weather = "Sunny, 25°C";
// Set cache options
var cacheOptions = new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10),
SlidingExpiration = TimeSpan.FromMinutes(2)
};
// Store data in cache
_cache.Set(cacheKey, weather, cacheOptions);
}
return Ok(weather);
}
}
The TryGetValue
method checks if the data is already in the cache. If not, it stores the
fetched data with specific expiration options.
// Example of Cache Options
var cacheOptions = new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5), // Data expires in 5 minutes
SlidingExpiration = TimeSpan.FromMinutes(1) // Resets expiration if accessed within 1 minute
};
_cache.Set("key", "value", cacheOptions);
Absolute Expiration: Ensures the data expires after a set duration.
Sliding Expiration: Extends the expiration time if the cache is accessed.
// Remove data from cache
_cache.Remove("weatherData");
Use the Remove
method to delete data from the cache when it is no longer valid.
// GET /api/weather
Response: "Sunny, 25°C"
// After Cache Expiration
GET /api/weather
Response: "Sunny, 25°C" (Data reloaded and cached again)
Test the caching behavior using tools like Postman or your browser.