Lesson 4 of 8
Output Caching (.NET 7+)
Output caching stores entire HTTP responses in memory or Redis - the next matching request is served directly from cache without executing the controller action. It's simpler than manual caching but less flexible. It's serverside caching distinct from browser Cache-Control.
Output Cache Policies
using Microsoft.AspNetCore.OutputCaching;
// ━━ Registration ━━
builder.Services.AddOutputCache(options =>
{
// Default policy - cache for 60 seconds
options.AddBasePolicy(builder =>
builder.Cache().Expire(TimeSpan.FromSeconds(60)));
// Named policy - for public product catalog
options.AddPolicy("ProductsCatalog", builder =>
builder.Cache()
.Expire(TimeSpan.FromMinutes(5))
.SetVaryByQuery("page", "pageSize", "category", "sort")
.Tag("products")); // tag for group invalidation
// User-specific - vary by Authorization header (don't cache admin responses for public)
options.AddPolicy("UserSpecific", builder =>
builder.Cache()
.Expire(TimeSpan.FromSeconds(30))
.SetVaryByHeader("Authorization"));
});
// In pipeline (after UseRouting, before endpoints):
app.UseOutputCache();
// ━━ Apply to actions ━━
[HttpGet]
[OutputCache(PolicyName = "ProductsCatalog")]
public async Task<IActionResult> GetAll([FromQuery] int page = 1) =>
Ok(await _service.GetPagedAsync(page));
[HttpGet("{id:guid}")]
[OutputCache(Duration = 300)] // 5 minutes, varies by route id automatically
public async Task<IActionResult> GetById(Guid id) => Ok();
// ━━ Cache invalidation via tags ━━
public class ProductsController(IOutputCacheStore cacheStore) : ControllerBase
{
[HttpPost]
public async Task<IActionResult> Create(CreateRequest req, CancellationToken ct)
{
var product = await _service.CreateAsync(req, ct);
// Invalidate all "products" tagged cache entries (the list endpoint)
await cacheStore.EvictByTagAsync("products", ct);
return CreatedAtAction(nameof(GetById), new { id = product.Id }, product);
}
}
interface IDotnetService { Task<dynamic> GetPagedAsync(int p); Task<dynamic> CreateAsync(dynamic r, CancellationToken ct); }
IDotnetService _service = null!;
record CreateRequest(string Name);Tip
Tip
Practice Output Caching NET 7 in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
.NET provides a unified platform for building various application types
Practice Task
Note
Practice Task - (1) Write a working example of Output Caching NET 7 from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Output Caching NET 7 is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.
Finished this lesson?