⚡ 100x Faster Responses with One Line of Code
Same endpoint called repeatedly? Database query every time? Output caching stores HTTP responses. No database, no processing.
📝 Basic Output Caching
// Program.cs
builder.Services.AddOutputCache();
app.UseOutputCache();
// Controller
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet]
[OutputCache(Duration = 60)] // Cache for 60 seconds
public async Task> GetProducts()
{
return await _context.Products.ToListAsync();
}
[HttpGet("{id}")]
[OutputCache(Duration = 300, VaryByQueryKeys = new[] { "id" })]
public async Task GetProduct(int id)
{
return await _context.Products.FindAsync(id);
}
}
🎯 Advanced Configuration
builder.Services.AddOutputCache(options =>
{
options.AddPolicy("LongCache", policy =>
{
policy.Expire(TimeSpan.FromHours(1))
.SetVaryByQuery("search", "page")
.Tag("products");
});
options.AddPolicy("NoCacheForAdmin", policy =>
{
policy.Expire(TimeSpan.FromSeconds(10))
.VaryByUser();
});
});
// Usage
[HttpGet]
[OutputCache(PolicyName = "LongCache")]
public async Task> GetProducts() { }
// Invalidate cache
[HttpPost]
public async Task CreateProduct(Product product)
{
await _context.Products.AddAsync(product);
await _context.SaveChangesAsync();
await _outputCacheStore.EvictByTagAsync("products", CancellationToken.None);
return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
}
💡 When to Use
- Read-only endpoints (GET requests)
- Public data (same for all users)
- Expensive database queries
- External API calls that change rarely
- Static reference data (country lists, categories)
“Homepage API called 10,000 times/minute. Database was dying. Added [OutputCache(Duration=5)]. Database load dropped 99%. Response time went from 200ms to 3ms.”
