diff --git a/docs/dotnet/asp.net/minimal-api.md b/docs/dotnet/asp.net/minimal-api.md index c08182d..187782d 100644 --- a/docs/dotnet/asp.net/minimal-api.md +++ b/docs/dotnet/asp.net/minimal-api.md @@ -263,3 +263,64 @@ In fact, the `user-jwts` tool utilizes the `user-secrets` infrastructure to mana ```sh dotnet user-jwts create # configure a dev JWT fot the current user ``` + +## Output Caching + +```cs +builder.Services.AddOutputCaching(); // no special options +builder.Services.AddOutputCaching(options => +{ + options => options.AddBasePolicy(x => x.NoCache()) // no cache policy + + Func predicate = /* discriminate requests */ + options.AddBasePolicy(x => x.With(predicate).CachePolicy()); + options.AddBasePolicy("", x => x.CachePolicy()); // named policy +}); + +// [...] + +app.UseOutputCaching(); // following middlewares can use output cache + +// [...] + +app.MapGet("/", RouteHandler).CacheOutput(); // cache forever +app.MapGet("/", RouteHandler).CacheOutput().Expire(timespan); + +app.MapGet("/", RouteHandler).CacheOutput(x => x.CachePolicy()); +app.MapGet("/", RouteHandler).CacheOutput(""); + +app.MapGet("/", RouteHandler).CacheOutput(x => x.VaryByHeader(/* headers list */)); +app.MapGet("/", RouteHandler).CacheOutput(x => x.VaryByQuery(/* query key */)); +app.MapGet("/", RouteHandler).CacheOutput(x => x.VaryByValue()); + +app.MapGet("/", [OutputCache(/* options */)]RouteHandler); +``` + +### Cache Eviction + +```cs + +app.MapGet("/", RouteHandler).CacheOutput(x => x.Tag("")); // tag cache portion + +app.MapGet("/", (IOutputCacheStore cache, CancellationToken token) => +{ + await cache.EvictByTag("", token); // invalidate a portion of the cache +}); +``` + +### Custom Cache Policy + +```cs +app.MapGet("/", RouteHandler).CacheOutput(x => x.AddCachePolicy()); +``` + +```cs +class CustomCachePolicy : IOutputCachePolicy +{ + public ValueTask CacheRequestAsync(OutputCacheContext context, CancellationToken cancellationToken) { } + + public ValueTask ServeFromCacheAsync(OutputCacheContext context, CancellationToken cancellationToken) { } + + public ValueTask ServeResponseAsync(OutputCacheContext context, CancellationToken cancellationToken) { } +} +```