C# Minimal API: Response Caching

Response Caching

Response caching reduces the number of requests a client or proxy makes to a web server. Response caching also reduces the amount of work the web server performs to generate a response. Response caching is set in headers. (Microsoft Docs)

Response caching is configured using the Cache-Control header, which allows responses to be cached on the client or along the way, for example on a proxy.

Response Caching in Minimal APIs

In ASP.NET Core MVC, response caching is typically configured using the ResponseCache attribute in combination with the UseResponseCaching middleware, but this is purely an MVC concept.

For Minimal APIs, we can achieve similar behavior by adding an endpoint filter that sets the Cache-Control header after the request is processed.

RouteHandlerBuilder Caching Extension

The following extension methods provide a simple way to apply response caching to Minimal API endpoints. The endpoint filter runs after the endpoint has processed the request and sets the Cache-Control header with the specified max age.

public static class HttpResponseCachingConfiguration
{
    private const int TenMinutes = 60 * 10;
    private const int Hour = 60 * 60;

    public static RouteHandlerBuilder AddResponseCacheTenMinutesHeader(this RouteHandlerBuilder routeHandlerBuilder)
      => routeHandlerBuilder.AddResponseCacheHeader(TenMinutes);

    public static RouteHandlerBuilder AddResponseCacheHourHeader(this RouteHandlerBuilder routeHandlerBuilder)
      => routeHandlerBuilder.AddResponseCacheHeader(Hour);

    public static RouteHandlerBuilder AddResponseCacheHeader(this RouteHandlerBuilder routeHandlerBuilder, int maxAgeInSeconds)
      => routeHandlerBuilder.AddEndpointFilter(async (context, next) =>
      {
          if (context.HttpContext.Response.StatusCode == StatusCodes.Status200OK)
          {
                    context.HttpContext.Response.Headers.CacheControl = $"public,max-age={maxAgeInSeconds}";
          }
          return await next(context);
      });
}

This extension makes it easy to attach caching headers to any Minimal API endpoint by chaining the extension method, as shown in the example below.

app.MapGet("https://dev.to/weatherforecast", () =>
{
    var forecast = Enumerable.Range(1, 5).Select(index =>
        new WeatherForecast
        (
            DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
            Random.Shared.Next(-20, 55),
            summaries[Random.Shared.Next(summaries.Length)]
        ))
        .ToArray();
    return forecast;
})
.AddResponseCacheHourHeader()
.WithName("GetWeatherForecast");

Note: Client-side caching in browsers or proxies requires caching to be enabled. Once cached, the client or proxy serves the cached response automatically when appropriate.

Important: Do not use public response caching for authenticated or user-specific endpoints.

When to use

Use response caching when responses are static, public and can be safely cached by browsers or proxies.

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post

ESAB Tracfinder Welding Tractors, ROBBI Mobile Cobot Welding System

Next Post

Why Creative & Performance Marketing Teams Fail Without the Right Talent Pipeline

Related Posts