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.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddResponseCaching(x => x.MaximumBodySize = 1024);
builder.Services.AddHttpClient("errorApi", c => { c.BaseAddress = new Uri("https://localhost:7250"); });
builder.Services.AddSingleton<IAsyncPolicy<HttpResponseMessage>>(httpRetryPolicy);
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
// UseCors must be called before UseResponseCaching
//app.UseCors();
app.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();
});
app.Run();
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:
[HttpGet]
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.