Skip to content

OutputCache Setup

Ieuan Walker edited this page Jan 27, 2026 · 2 revisions

This library doesn’t replace ASP.NET Core output caching - it just has some extra features

1. Register output caching services

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddOutputCache(options =>
{
	// Optional: configure base policies here
});

builder.AddEndpoints();

var app = builder.Build();

2. Add middleware (order matters)

Output caching is middleware-driven, so pipeline order is important.

A safe default ordering is:

  1. Routing (Map... / endpoint mapping)
  2. Authentication (UseAuthentication())
  3. Authorization (UseAuthorization())
  4. Output caching (UseOutputCache())

Example:

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

// Important: place output caching AFTER authentication/authorization
// so the cache can correctly consider authenticated/unauthenticated behavior.
app.UseOutputCache();

app.MapEndpoints();

app.Run();

If UseOutputCache() is placed before authentication/authorization you can get unexpected behavior, including caching the wrong variant of a response.

3. Cache an endpoint

Output caching is configured using the endpoint’s RouteHandlerBuilder.

public class HelloWorldEndpoint : IEndpointWithoutRequest<string>
{
	public static void Configure(RouteHandlerBuilder builder)
	{
		builder
			.Get("/hello")
			.CacheOutput(TimeSpan.FromMinutes(5));
	}

	public Task<string> Handle(CancellationToken ct)
	{
		return Task.FromResult("Hello");
	}
}

Clone this wiki locally