Search
K
  1. Response Caching

Response Caching

In order to get response caching working, you need to enable the response caching middleware and specify options for caching using the ResponseCache() method in the endpoint configuration. This method supports all arguments of the [ResponseCache] attribute you'd typically use with mvc except for the CacheProfileName argument as cache profiles are not supported.

Note: Response caching is not the same thing as Output caching. Response caching does not store anything on the server itself and simply manipulates headers with instructions on how to cache the responses downstream in web browsers, proxy servers etc. Output caching on the other hand stores responses on the server either in-memory or via a cache storage provider such as Redis. See this document for more details on response caching in ASP.NET.

Program.cs
var bld = WebApplication.CreateBuilder();
bld.Services
   .AddFastEndpoints()
   .AddResponseCaching(); //add this

var app = bld.Build();
app.UseResponseCaching() //add this before FE
   .UseFastEndpoints();
app.Run();
MyEndpoint.cs
public class MyEndpoint : EndpointWithoutRequest
{
    public override void Configure()
    {
        Get("/api/cached-ticks");
        ResponseCache(60); //cache for 60 seconds
    }

    public override Task HandleAsync(CancellationToken ct)
    {
        return SendAsync(new
        {
            Message = "this response is cached"
            Ticks = DateTime.UtcNow.Ticks
        });
    }
}

TIP

Output caching features introduced in .NET 7.0 can be added to endpoints via the CacheOutput(...) extension method.

public override void Configure()
{
    ...
    Options(x => x.CacheOutput(p => p.Expire(TimeSpan.FromSeconds(60))));
}

© FastEndpoints 2024