Response Caching in .Net 6

This post explains how to configure Response Caching Middleware in an ASP.NET Core app using .Net 6. The middleware determines when responses are cacheable, stores responses, and serves responses from cache.

Caching response helps improve the performance and response time of Web APIs where it is possible. But it takes some effort to build out a caching infrastructure and manage it. The Response caching middleware which comes out of the box simplifies the implementation significantly. And also it does not require building custom implementation for caching, plus provides clients the option to choose whether to use a cached value or not.

Create a .Net 6 API, and modify the Program.cs file as below:

using Polly;
using Polly.Extensions.Http;

var builder = WebApplication.CreateBuilder(args);
var httpRetryPolicy = Policy.HandleResult<HttpResponseMessage>(r => !r.IsSuccessStatusCode)
    //.CircuitBreakerAsync(2, TimeSpan.FromSeconds(30));
    .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(retryAttempt));

// Add services to the container.

// Learn more about configuring Swagger/OpenAPI at
builder.Services.AddResponseCaching(x => x.MaximumBodySize = 1024);
builder.Services.AddHttpClient("errorApi", c => { c.BaseAddress = new Uri("https://localhost:7250"); });

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())




// UseCors must be called before UseResponseCaching


app.Use(async (context, next) =>
    context.Response.GetTypedHeaders().CacheControl =
        new Microsoft.Net.Http.Headers.CacheControlHeaderValue()
            Public = true,
            MaxAge = TimeSpan.FromSeconds(10)

    context.Response.Headers[Microsoft.Net.Http.Headers.HeaderNames.Vary] = new string[] { "Accept-Encoding" };
    await next();


This API adds headers to control caching on subsequent requests:

  • Cache-Control: Caches cacheable responses for up to 10 seconds.
  • Vary: Configures the middleware to serve a cached response only if the Accept-Encoding header of subsequent requests matches that of the original request.

Add a ValuesController.cs and a simple Get endpoint:

public int Get()
    return DateTime.Now.Second;

Run the API and hit the Get endpoint through Postman and add Cache-Control Header with value “public” and you’ll observe the cached response for 10 seconds.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.