How do you implement caching in ASP.NET Core?

Answer

ASP.NET Core offers several caching layers. In-memory cache: builder.Services.AddMemoryCache();. Inject IMemoryCache: if (!_cache.TryGetValue("key", out MyData data)) { data = await FetchDataAsync(); _cache.Set("key", data, TimeSpan.FromMinutes(5)); }. Node-local only — data lost on restart/scale-out. Distributed cache: interface IDistributedCache — shared across multiple server instances. Implementations: Redis (AddStackExchangeRedisCache), SQL Server (AddDistributedSqlServerCache). Stores byte arrays — use JSON serialization. Output caching (ASP.NET Core 7+): cache HTTP responses at the middleware level: app.UseOutputCache(); [OutputCache(Duration = 60)]. Response caching: sends Cache-Control headers to CDNs and browsers. HybridCache (.NET 9+): L1 (in-memory) + L2 (distributed) in one API with stampede protection. Cache-aside pattern is most common. Always consider: cache invalidation strategy, cache stampede (use locking or HybridCache), and memory pressure.