Caching in ASP.NET Core allows developers to store frequently accessed data temporarily, reducing server load and improving app performance. ASP.NET Core supports in-memory caching, distributed caching, and response caching.
Key Features:
- In-memory caching for single-server apps
- Distributed caching for multi-server or cloud apps
- Supports expiration, sliding, and absolute timeouts
- Improves performance and scalability
- Easy integration with controllers and services
Example – In-memory Caching:
builder.Services.AddMemoryCache();
var app = builder.Build();
app.MapGet("/time", (IMemoryCache cache) =>
{
if(!cache.TryGetValue("CurrentTime", out string currentTime))
{
currentTime = DateTime.Now.ToString();
cache.Set("CurrentTime", currentTime, TimeSpan.FromSeconds(30));
}
return currentTime;
});
app.Run();
Caching in ASP.NET Core boosts app responsiveness and reduces repeated computation or database calls, ensuring faster user experiences.
Citations: