🚀 Key Takeaways: Output caching stores entire API responses. Perfect for GET endpoints with static or semi-static data.
Your API does the same computation repeatedly. Output caching removes that need.
🚀 Setup Output Caching
// Program.cs - Enable output caching
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOutputCache(options =>
{
// ✅ Cache configuration
options.AddBasePolicy(builder => builder
.With(c => c.HttpContext.Request.Method == "GET")
.Expire(TimeSpan.FromMinutes(5))
);
// ✅ Named cache policy
options.AddPolicy("LongCache", policy => policy
.Expire(TimeSpan.FromHours(1))
.Tag("long-cache")
);
// ✅ Vary by header
options.AddPolicy("VaryByAcceptLanguage", policy => policy
.VaryByHeader("Accept-Language")
.Expire(TimeSpan.FromMinutes(10))
);
// ✅ Vary by query parameter
options.AddPolicy("VaryByQuery", policy => policy
.VaryByQuery("page", "size")
.Expire(TimeSpan.FromMinutes(5))
);
});
app.UseOutputCache();
// ✅ Simple caching
app.MapGet("/api/products", async (IProductService service) =>
{
return await service.GetProductsAsync();
}).CacheOutput();
// ✅ Custom cache policy
app.MapGet("/api/products/{id}", async (int id, IProductService service) =>
{
return await service.GetProductAsync(id);
}).CacheOutput(policy => policy
.Expire(TimeSpan.FromMinutes(5))
.VaryByRouteValue("id")
);
// ✅ Cache invalidation
app.MapPost("/api/products", async (Product product, IProductService service) =>
{
var result = await service.CreateProductAsync(product);
// ✅ Invalidate cache
return Results.Created($"/api/products/{result.Id}", result);
});
💡 Advanced: Custom Cache Key
// ✅ Custom cache key with user context
public class UserContextCacheKey : IOutputCacheKey
{
public string GetCacheKey(HttpContext context)
{
var userId = context.User.FindFirst("sub")?.Value ?? "anonymous";
var path = context.Request.Path.ToString();
return $"user_{userId}_{path}";
}
}
// Register custom key
builder.Services.AddSingleton();
// ✅ Cache with dependencies
[ApiController]
[Route("api/[controller]")]
public class OrdersController : ControllerBase
{
[HttpGet]
[OutputCache(Duration = 60, VaryByHeader = "Authorization")]
public async Task GetOrders()
{
// Cached for 60 seconds
// Varies by Authorization header (user-specific)
return Ok(await _orderService.GetOrdersAsync());
}
[HttpDelete("{id}")]
public async Task DeleteOrder(int id)
{
await _orderService.DeleteAsync(id);
// ✅ Cache automatically invalidated
return NoContent();
}
}
📊 Output Cache Results
| Endpoint | Without Cache | With Cache | Speedup |
|---|---|---|---|
| /api/products | 450ms | 4ms | 112x |
| /api/orders | 280ms | 3ms | 93x |
| /api/reports | 1200ms | 5ms | 240x |
