IDistributedCache is an ASP.NET Core service for caching data values across requests. Its underlying storage accepts byte arrays; string extension methods provide a convenient way to store calculated results. The endpoint can depend on the interface while service registration selects the cache implementation. section 17.2.1
Cache a calculated sum
For a `/sum/{count}` endpoint, use a key such as `sum_{count}` and call `GetStringAsync`. On a miss, calculate the sum and store it with `SetStringAsync`. Set `DistributedCacheEntryOptions.AbsoluteExpirationRelativeToNow` to two minutes so the result is eventually ejected. A time included in the stored string makes reuse visible when `/sum` is reloaded. section 17.2.1
Listing 17.5 Using the cache service in the SumEndpoint.cs file in the Platform folder
using Microsoft.Extensions.Caching.Distributed;
namespace Platform {
public class SumEndpoint {
public async Task Endpoint(HttpContext context,
IDistributedCache cache) {
int count;
int.TryParse((string?)context.Request.RouteValues["count"],
out count);
string cacheKey = $"sum_{count}";
string? totalString = await cache.GetStringAsync(cacheKey);
if (totalString == null) {
long total = 0;
for (int i = 1; i <= count; i++) {
total += i;
}
totalString = $"({DateTime.Now.ToLongTimeString()}) "
+ total;
await cache.SetStringAsync(cacheKey, totalString,
new DistributedCacheEntryOptions {
AbsoluteExpirationRelativeToNow =
TimeSpan.FromMinutes(2)
});
}
await context.Response.WriteAsync(
$"({DateTime.Now.ToLongTimeString()}) Total for {count}"
+ $" values:\n{totalString}\n");
}
}
}
See the endpoint’s cache lookup, calculation, and write in `SumEndpoint.cs`. section 17.2.1
Register an implementation before using the service. `AddDistributedMemoryCache` keeps values in memory; its `SizeLimit` can constrain the cache, but memory allocation needs balancing against server resources. `AddStackExchangeRedisCache` and `AddDistributedSqlServerCache` are other available registration methods. section 17.2.1
Listing 17.6 Adding a service in the Program.cs file in the Platform folder
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDistributedMemoryCache(opts => {
opts.SizeLimit = 200;
});
var app = builder.Build();
app.MapEndpoint<Platform.SumEndpoint>("/sum/{count:int=1000000000}");
app.MapGet("/", async context => {
await context.Response.WriteAsync("Hello World!");
});
app.Run();
See the in-memory registration and `/sum` route in `Program.cs`. section 17.2.1
For a persistent shared cache, create the SQL Server cache table, install `Microsoft.Extensions.Caching.SqlServer`, and register `AddDistributedSqlServerCache` with a connection string, schema, and table name. The `/sum` response need not change, but a cached value can survive an ASP.NET Core restart. Values in IDistributedCache are shared between requests; use session middleware for per-user values. Session middleware itself stores data through IDistributedCache. section 17.2.2
Listing 17.13 Using a persistent data cache in the Program.cs file in the Platform folder
var builder = WebApplication.CreateBuilder(args);
//builder.Services.AddDistributedMemoryCache(opts => {
// opts.SizeLimit = 200;
//});
builder.Services.AddDistributedSqlServerCache(opts => {
opts.ConnectionString
= builder.Configuration["ConnectionStrings:CacheConnection"];
opts.SchemaName = "dbo";
opts.TableName = "DataCache";
});
var app = builder.Build();
app.MapEndpoint<Platform.SumEndpoint>("/sum/{count:int=1000000000}");
app.MapGet("/", async context => {
await context.Response.WriteAsync("Hello World!");
});
app.Run();
See how `Program.cs` replaces the in-memory registration with SQL Server cache configuration. section 17.2.2

