In today’s newsletter we are going to discuss
What is response caching
Its benefits
Methods that support it
Implementation in .NET 6
Caching attributes explanation
Real world examples
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
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)]
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 to "public".
Client :- Cached only in the client and sets "Cache-control" header to "private".
None :- "Cache-control" and "Pragma" headers are set to "no-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
Promote yourself to 3700+ subscribers by sponsoring my Newsletter (Reach me at mwaseemzakir@gmail.com)
Become a Patron and get access to 120+ .NET Questions and Answers , I add 2-5 new questions every week
Get my FREE eBook from Gumroad that contains 30 .NET Tips (Downloaded by 2300+ and 100+ five star ratings)
Special Offers 📢
Ultimate ASP.NET Core Web API Second Edition - Premium Package
10% off with discount code: 9s6nuez
Can you please make EP .azure .net and all must important service releted to developer
Also for kubernate and docker