I wanted to try caching mechanism in my .NET core API project.
I followed this article to configure the middleware https://thecodeblogger.com/2021/06/06/middleware-for-response-caching-in-net-core-web-apis/
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
// 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;
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
// Response Caching Middleware
app.UseResponseCaching();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
The controller
[HttpGet]
[ResponseCache(NoStore = false, Duration = 600, Location = ResponseCacheLocation.Any)]
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
And I can see in the response this header
Cache-Control : public,max-age=600
So I put a break point in the controller, whenever I call the api thorugh postman or browsers it hit the api.
I was assuming adding the header Cache-Control: public,max-age=600
will create a cache of the response in the client for 600 seconds and it won't hit the backend for each request.
If not, then what is the actual point of the Cache-Control
Most browser will have in the request header Cache-Control: max-age=0
which will override the response header's Cache-Control, forcing the response to not be cached.
For the Chrome browser, to not pass this Cache-Control: max-age=0
header, open the Chrome console and type
location = "https://your.page.com"
In your application codebase, you can set the request header to null to remove the default Cache-Control: max-age=0
header.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.