In short, using a ResponseCache attribute like the following is enough to get client-side expiration caching to work in a completely new default dotnet base project (including async methods):
[HttpGet] [ResponseCache(Duration = 120)] public IEnumerable<StateProvinceLookupModel> GetStateProvinces() { return _domain.GetStateProvinces(); }
This works correctly in the screenshot above, since Cache-Control: public,max-age=120 is visible there. In most cases, browsers will not send subsequent requests until the expiration date (i.e. within the next 120 seconds or 2 minutes), but this is the solution of the browser (or another client).
If the request is sent independently, you either have middleware or a server configuration that overwrites the response headers, or your client ignores the caching directive. In the screenshot above, the client ignores caching because it contains the header of the cache control.
Common cases where the client cache is ignored and the request is sent:
- Chrome prevents any caching when using HTTPS without a certificate (or an invalid certificate, this is common with local development, so be sure to use HTTP when testing the cache or trust a self-signed certificate)
- Most browser developer tools disable caching by default when opened, this can be disabled
- Browsers usually send extra headers, Chrome sends
Cache-Control: no-cache
- Updating directly (i.e. Ctrl + F5) will cause most browsers not to use the cache and make a request regardless of age
- Browsers usually send extra headers, Chrome sends
Cache-Control: max-age=0 (this can be seen in the screenshot)
- The postman sends the
Cache-Control: no-cache header Cache-Control: no-cache which allows you to bypass the local cache, which leads to sending requests; You can disable it in the settings dialog box, in which case requests will no longer be sent with the above client cache configuration
At the moment, we have gone beyond the expiration-based client caching, and the server will somehow receive a request, and a different level of caching will occur: you can force the server to respond with 304 Not Modified code (which then works again for the client to interpret in any way, which he wants) or use the server-side cache and respond with full content. Or you can’t use any subsequent caching and just do all the request processing again on the server.
Note. The ResponseCache attribute should not be confused with services.AddResponseCaching() & app.UseResponseCaching() middleware in the startup configuration, as it is designed for server-side caching (which by default uses a cache in memory when using middleware).). Middleware is not required for client caching, the attribute alone is sufficient.
John weisz
source share