Middleware For Response Caching in .NET Core Web APIs
.NET Core Web API and Response Caching Middleware

Middleware For Response Caching in .NET Core Web APIs

In previous article, we have seen how ResposneCacheAttribute can be placed on controller actions to emit appropriate HTTP headers which can instruct internet caches to cache the response.

We also have seen that in order to use VaryByQueryKeys strictly needs response caching middleware configured in the request pipeline. So, in this article, we will quickly see how response caching middleware can be configured in startup.

What does the middleware do ?

Response caching middleware determines when the responses are cacheable.

If they are cacheable, then middleware stores them in cache. It also serves those responses from cache to subsequent requests.

How to configure it ?

Like any other middleware, configuring this middleware is a two step process:

  • AddResponseCaching call needs to be added under Startup.ConfigureServices. This registers all the dependencies required by middleware.
  • UseResponseCaching call needs to be added under Startup.Configure. This registers middleware in request processing pipeline.

UseResponseCaching takes 3 options as input:

  • MaximumBodySize – default is 64 MB. It defines largest response size that can be cached.
  • UseCaseSensitivePaths– default is false. This determines if the case sensitive comparison should be performed on paths.
  • SizeLimit – default is 100 MB. It determines maximum size for middleware cache.

Passing these three options is not mandatory. If not passed, middleware initiates these settings with default values. Below is a code example for registering the middleware. It also sets three options mentioned above.

UseCors must be called before UseResponseCaching when using CORS middleware.

// Startup.cs
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Response Caching Middleware
services.AddResponseCaching(options =>
{
// Each response cannot be more than 1 KB
options.MaximumBodySize = 1024;
// Case Sensitive Paths
// Responses to be returned only if case sensitive paths match
options.UseCaseSensitivePaths = true;
});
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc(
"v1", new OpenApiInfo { Title = "WebApiResponseCachingDemo", Version = "v1" });
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(
c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebApiResponseCachingDemo v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
// CORS Should be before Response Caching
app.UseCors();
// Response Caching Middleware
app.UseResponseCaching();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
// ValuesController.cs
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
// ResponseCacheAttribute is to set caching headers
[HttpGet]
[ResponseCache(NoStore = false, Duration = 10, Location = ResponseCacheLocation.Any)]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2", DateTime.Now.ToString() };
}
}
view raw Startup.cs hosted with ❤ by GitHub

I hope this information was useful. Let me know your thoughts.

Leave a Reply