Search⌘ K
AI Features

Varying Cached Data by Query String

Explore how to manage output caching in ASP.NET Core MVC by customizing cache variation through query string parameters. Learn to disable unnecessary cache duplication, implement policies to specify relevant query strings, and observe how these adjustments affect cached page responses. Understand techniques to optimize caching when query strings impact content, improving website scalability and performance.

We'll cover the following...

If a value is different in the relative path, then output caching automatically treats the request as a different resource and so caches different copies for each, including differences in any query string parameters. Consider the following URLs:

Shell
{{EDUCATIVE_LIVE_VM_URL}}:5001/Home/ProductDetail/12
{{EDUCATIVE_LIVE_VM_URL}}:5001/Home/ProductDetail/29
{{EDUCATIVE_LIVE_VM_URL}}:5001/Home/ProductDetail/12?color=red
{{EDUCATIVE_LIVE_VM_URL}}:5001/Home/ProductDetail/12?color=blue

All four requests will each have their own cached copy of their own page. If the query string parameters have no effect on the generated page, then that is a waste.

Fixing the problem

Let’s see how we can fix this problem. We will start by disabling varying the cache by query string parameter values and then implement some page functionality that uses a query string parameter:

Step 1: In Program.cs, in the call to AddOutputCache, increase the default expiration to 20 seconds, and add a statement to define a named policy to disable ...