In previous article, we have seen how ResposneCacheAttribute can be placed on controller actions to emit appropriate HTTP headers which can instruct internet caches to cache the response.
We also have seen that in order to use VaryByQueryKeys strictly needs response caching middleware configured in the request pipeline. So, in this article, we will quickly see how response caching middleware can be configured in startup.
What does the middleware do ?
Response caching middleware determines when the responses are cacheable.
If they are cacheable, then middleware stores them in cache. It also serves those responses from cache to subsequent requests.
How to configure it ?
Like any other middleware, configuring this middleware is a two step process:
- AddResponseCaching call needs to be added under
Startup.ConfigureServices. This registers all the dependencies required by middleware.
- UseResponseCaching call needs to be added under
Startup.Configure. This registers middleware in request processing pipeline.
UseResponseCaching takes 3 options as input:
- MaximumBodySize – default is 64 MB. It defines largest response size that can be cached.
- UseCaseSensitivePaths– default is false. This determines if the case sensitive comparison should be performed on paths.
- SizeLimit – default is 100 MB. It determines maximum size for middleware cache.
Passing these three options is not mandatory. If not passed, middleware initiates these settings with default values. Below is a code example for registering the middleware. It also sets three options mentioned above.
UseCors must be called before UseResponseCaching when using CORS middleware.
I hope this information was useful. Let me know your thoughts.