0
votes

I'm new to asp.net core sorry if my question sounds dumb. We can use response caching by

//ConfigureServices
services.AddResponseCaching();

//Configure
app.UseResponseCaching();

But isn't that the purpose of response cache is to add a Cache-Control header in the response so that clients(browser) will cache this response locally. So why not just manually add the header to the httpcontext as context.Response.Headers["Cache-Control"] = "public, max-age=120"; why all the fuss to use a dedicated response caching middleware?

1
why all the fuss It doesn't seem like much fuss. - mjwills

1 Answers

1
votes

But isn't that the purpose of response cache is to add a Cache-Control header in the response so that clients(browser) will cache this response locally.

From my understanding, there can be a cache-control header in both the API request and API response. The cache-control header in the API request tells the server if the response should or should not be served from cache. The one is the API response tells the client if the response should or should not be cached locally. See here.

With regards to the Response Caching Middleware in ASP.NET Core:

The Response Caching middleware only acts on the API request - it checks for the presence of cache-control headers and depending on the value, will attempt to serve the response from cache. In other words, it will not add cache-control headers to the API response, it will only respect the cache-control headers in the API request. Per the MSFT documentation:

The middleware determines when responses are cacheable, stores responses, and serves responses from cache.

You can verify this behavior in the Middleware implementation here.