Merge branch 'main' into dotnet/net-7

This commit is contained in:
Marcello 2022-11-08 17:49:24 +01:00 committed by GitHub
commit 619844447a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -324,3 +324,64 @@ class CustomCachePolicy : IOutputCachePolicy
public ValueTask ServeResponseAsync(OutputCacheContext context, CancellationToken cancellationToken) { }
}
```
## Output Caching
```cs
builder.Services.AddOutputCaching(); // no special options
builder.Services.AddOutputCaching(options =>
{
options => options.AddBasePolicy(x => x.NoCache()) // no cache policy
Func<OutputCacheContext, bool> predicate = /* discriminate requests */
options.AddBasePolicy(x => x.With(predicate).CachePolicy());
options.AddBasePolicy("<policy-name>", x => x.CachePolicy()); // named policy
});
// [...]
app.UseOutputCaching(); // following middlewares can use output cache
// [...]
app.MapGet("/<route>", RouteHandler).CacheOutput(); // cache forever
app.MapGet("/<route>", RouteHandler).CacheOutput().Expire(timespan);
app.MapGet("/<route>", RouteHandler).CacheOutput(x => x.CachePolicy());
app.MapGet("/<route>", RouteHandler).CacheOutput("<policy-name>");
app.MapGet("/<route>", RouteHandler).CacheOutput(x => x.VaryByHeader(/* headers list */));
app.MapGet("/<route>", RouteHandler).CacheOutput(x => x.VaryByQuery(/* query key */));
app.MapGet("/<route>", RouteHandler).CacheOutput(x => x.VaryByValue());
app.MapGet("/<route>", [OutputCache(/* options */)]RouteHandler);
```
### Cache Eviction
```cs
app.MapGet("/<route-one>", RouteHandler).CacheOutput(x => x.Tag("<tag>")); // tag cache portion
app.MapGet("/<route-two>", (IOutputCacheStore cache, CancellationToken token) =>
{
await cache.EvictByTag("<tag>", token); // invalidate a portion of the cache
});
```
### Custom Cache Policy
```cs
app.MapGet("/<route-one>", RouteHandler).CacheOutput(x => x.AddCachePolicy<CustomCachePolicy>());
```
```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) { }
}
```