Building RESTful Web Services with .NET Core
上QQ阅读APP看书,第一时间看更新

Caching

To avoid generating the same data with every request, there is a technique called caching that is used to store the data either on the client's or the server's side. This cached data may be used for further reference whenever it is required.

When using caching, it is important that you manage it properly. The reason for this is simple. We are storing data that won't be replaced by fresh data from the server. While this is an advantage that increases the performance of the service, at the same time, if we are not careful as to what to cache and configure during its lifetime, we might end up seeing outdated data. For example, suppose we are showing the live price of gold on our website and we cached this figure. The next time the price changes, it won't be reflected unless we expire the cache that was previously stored.

Let's look at the different kinds of HTTP headers and how to configure caches:

The configuration of the preceding five headers depends upon the nature of the service. Take the example of the service that provides the live price of gold—ideally, it would have the cache age limit as low as possible, or even have caching turned off, because users should see the latest results every time they refer to the site.

However, a site that contains many images would hardly change or update them. In that case, the cache can be configured to store them for a longer duration.

These header values are consulted in accordance with the cache-control header to check whether the cached results are still valid or not.

The following are the most common values for the cache-control header: