Response caching in .NET Core
What is response caching
Response caching is a technique for storing the responses of an API or web application in a cache so that they can be served faster to subsequent requests.
The responses are stored in a cache with a key that uniquely identifies them, and the cache has a limited size and a policy for removing items when it becomes full.
Benefits of response caching
Improved performance by reducing the load on the server.
Reduced server load, as it can serve the cached response instead of generating a new one.
Reduced bandwidth usages it reduces the amount of data that needs to be transferred between the server and the client.
Improved security as it can reduce the number of requests that reach the server, reducing the risk of certain types of attacks.
Methods supported
We can apply caching on following methods :
- Get
- Head
Implementation in .NET 6
- Step 1 : Configure Program.cs :
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddResponseCaching();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseCors();
app.UseResponseCaching();
app.UseAuthorization();
app.MapControllers();
app.Run();
Make sure CORS is called before UseResponseCaching
-
Step 2 : Use caching on controller/method
This is example of method level caching , we have added this line of code
[ResponseCache(Duration = 30, Location = ResponseCacheLocation.Client)]
[HttpGet(Name = "GetWeatherForecast")]
[ResponseCache(Duration = 30, Location = ResponseCacheLocation.Client)]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
}).ToArray();
}
For controller level we add same line , difference is that we put it on controller instead of method
Caching attributes explained
Duration = 30
It sets max-age in cache-control header in seconds
Location = ResponseCacheLocation.Client
It sets the location where would the data cache.
ResponseCacheLocation
has three values Any
,Client
and None
-
Any :- Cached in both proxies and client and sets
Cache-control
header topublic
. -
Client :- Cached only in the client and sets
Cache-control
header toprivate
. -
None :-
Cache-control
andPragma
headers are set tono-cache
.
Real world Examples of Caching
- News website
- E-commerce websites
In your application you can apply response caching to those requests whose response is changed after a time and you are sure about it.
How to verify that cache has been implemented ?
Create an application apply caching and then request it from Postman and set time to 60 minutes, you will notice that only first request will reach the controller, after that even if you try request will not reach controller
Whenever you're ready, there are 3 ways I can help you:
- Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
- Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
- Patreon community : Get access to all of my blogs and articles at one place