Skip to content

Invalidate cache

Ieuan Walker edited this page Apr 5, 2026 · 1 revision

You can invalidate endpoint caches programmatically.

  1. Add a tag to the endpoint cache
public class GetItemsEndpoint : IEndpointWithoutRequest<List<ItemModel>>
{
	public static string CacheKey = "GetItemsEndpointCacheKey";

	public static void Configure(RouteHandlerBuilder builder)
	{
		builder
			.Get("/items")
			.CacheOutput(TimeSpan.FromMinutes(5)).Tag(CacheKey);
	}

	public async Task<ItemModel> Handle(CancellationToken ct)
	{
		...
	}
}
  1. Invalidate the cache by injecting IOutputCacheStore
public class PostItemEndpoint : IEndpointWithoutRequest<List<ItemModel>>
{
	readonly IOutputCacheStore _outputCache;

	public PostItemEndpoint(IOutputCacheStore outputCache)
	{
		_outputCache = outputCache ?? throw new ArgumentNullException(nameof(outputCache));
	}

	public static void Configure(RouteHandlerBuilder builder)
	{
		...
	}

	public async Task<ItemModel> Handle(CancellationToken ct)
	{
		...

		await _outputCache.EvictByTagAsync(GetItemsEndpoint.CacheKey, default);
	}
}

Clone this wiki locally