Note: Response/Output cache handled by their respective middlewares and do not hit controller in subsequent requests until cache invalidated.
Data Cache (IMemorycache, Memcache, Redis): Managed by code, you check in code if data available in cache then serve else reproduce and serve.
1. Output Caching (Recommended for .NET 7+)
Starting in ASP.NET Core 7+, Microsoft introduced built-in Output Caching Middleware, which is the best way to cache full API responses.
Step 1: Register Output Caching
In Program.cs:
Step 2: Apply Caching to an Endpoint
🔹 This caches the response for 60 seconds.
🔹 Works great for GET endpoints.
Advanced Example (Custom Policy)
Then:
2. Response Caching (HTTP Cache Headers)
This uses HTTP headers like Cache-Control. It works with browser/proxy caching.
Enable Middleware
Use Attribute
🔹 This sets HTTP headers.
🔹 It does NOT cache on the server by default.
🔹 Good for public APIs.
3. Data Cache
In-Memory Caching (IMemoryCache)
Best when you want to cache data, not full HTTP responses.
Register
Use in Controller
4. Distributed Caching (Redis, SQL Server)
For multi-server environments, use distributed cache.
Common choice:
-
Redis: Redis can store complex data types like Lists, arrays, Hash tables etc.
Memcached: Simple text string store
Example Setup with Redis
Then inject IDistributedCache.
| Feature | Memcached | Redis |
|---|
| Distributed | Yes | Yes |
| Replication | No (basic) | Yes |
| Persistence | No | Yes |
| Data loss risk | Higher | Lower |
| Complexity | Simple | Advanced |
Which One Should You Use?
| Scenario | Recommended |
|---|
| Cache full API response | OutputCache |
| Scale across multiple servers | Redis (Distributed Cache) |
| Cache DB results only | IMemoryCache |
| Browser/proxy caching | ResponseCache |
Best Practice Tips
-
Cache only GET requests.
- Avoid caching user-specific data unless using
VaryBy. - Always define expiration.
- Invalidate cache on data update.
- Use distributed cache in production with multiple instances.
Output cache and Response Cache both stores whole response handled by middleware, only difference is storage location.
Response Caching vs Output Caching
| Feature | Response Caching | Output Caching |
|---|
| Where caching happens | Client / Proxy (browser, CDN) | Server (inside ASP.NET Core) |
| Middleware | UseResponseCaching() | UseOutputCache() |
| Actually stores response on server? | No | Yes |
| Performance benefit for server | Minimal | Significant |
| Best for | Public APIs | High-performance APIs |
| Introduced | Early ASP.NET Core versions | .NET 7 |