...

/

Varying Cached Data by Query String

Varying Cached Data by Query String

Learn about configuring output caching in ASP.NET Core and implementing functionality based on query string values.

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:

Press + to interact
{{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 varying by query ...