Introduction
When building modern web APIs, performance is one of the most critical factors. Users expect fast responses, and systems need to handle high traffic efficiently. One of the best ways to improve API performance is by using response caching.
Response caching allows your API to store the result of a request and reuse it for subsequent requests instead of processing the same logic again. This reduces server load, improves response time, and enhances scalability.
In this article, we will understand what response caching is, how it works, and how to implement it step by step in ASP.NET Core Web API using simple and practical examples.
What is Response Caching?
Response caching is a technique where the server stores HTTP responses and returns the cached response for identical requests.
Instead of executing the same controller logic repeatedly, the server sends the previously stored response if the request matches specific conditions.
This is especially useful for:
Benefits of Response Caching
How Response Caching Works in ASP.NET Core
ASP.NET Core uses HTTP headers to control caching behavior. The Response Caching Middleware looks at these headers and decides whether to cache or serve a cached response.
Some important headers include:
Step 1: Create a New ASP.NET Core Web API Project
You can create a new project using Visual Studio or CLI:
dotnet new webapi -n ResponseCachingDemo
cd ResponseCachingDemo
Step 2: Add Response Caching Services
Open Program.cs and register response caching services:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddResponseCaching();
var app = builder.Build();
app.UseHttpsRedirection();
// Enable Response Caching Middleware
app.UseResponseCaching();
app.MapControllers();
app.Run();
Step 3: Create a Sample Controller
Create a controller to demonstrate caching behavior:
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet]
public IActionResult GetProducts()
{
var data = new
{
Time = DateTime.Now,
Message = "Fresh Data from Server"
};
return Ok(data);
}
}
If you call this API multiple times, you will see the time changes every time because caching is not applied yet.
Step 4: Enable Response Caching Using Attributes
Now apply the ResponseCache attribute to cache the response:
[HttpGet]
[ResponseCache(Duration = 60, Location = ResponseCacheLocation.Any, NoStore = false)]
public IActionResult GetProducts()
{
var data = new
{
Time = DateTime.Now,
Message = "Fresh Data from Server"
};
return Ok(data);
}
Explanation:
Duration = 60 → Cache response for 60 seconds
Location = Any → Cache can be stored anywhere (client or proxy)
NoStore = false → Allows caching
Now when you hit the API multiple times within 60 seconds, you will get the same response.
Step 5: Understanding Cache-Control Header
The ResponseCache attribute automatically sets HTTP headers like:
Cache-Control: public,max-age=60
This tells browsers and proxies to cache the response for 60 seconds.
Step 6: Using VaryByQueryKeys
If your API depends on query parameters, you can cache different responses for different queries.
Example:
[HttpGet]
[ResponseCache(Duration = 60, VaryByQueryKeys = new[] { "id" })]
public IActionResult GetProductById(int id)
{
var data = new
{
ProductId = id,
Time = DateTime.Now
};
return Ok(data);
}
Now each unique id will have its own cached response.
Step 7: Controlling Caching Behavior
You can disable caching when needed:
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
Use this for:
Sensitive data
User-specific responses
Step 8: Important Limitations
Works only for GET requests
Does not cache responses with Authorization headers by default
Middleware must be enabled
Not suitable for dynamic or user-specific data
Step 9: Response Caching vs In-Memory Caching
Difference between Response Caching and In-Memory Caching:
| Feature | Response Caching | In-Memory Caching |
|---|
| Level | HTTP Layer | Application Layer |
| Storage | Client/Proxy | Server Memory |
| Use Case | API responses | Complex data objects |
| Control | Headers | Code-based |
Step 10: Best Practices
Use caching for read-only endpoints
Avoid caching sensitive data
Use short durations for dynamic data
Combine with CDN for better performance
Monitor cache hit ratio
Real-World Example
Imagine an e-commerce API:
This improves performance without affecting data accuracy.
Conclusion
Response caching in ASP.NET Core Web API is a simple yet powerful way to improve performance and scalability. By storing responses and reusing them, you reduce unnecessary processing and deliver faster results to users.
By following the step-by-step approach in this article, you can easily implement response caching in your API and optimize your application's performance.
Start small, test your caching strategy, and gradually optimize it based on your application's needs.