Tuesday, October 12, 2021

ASP.NET Core - InvalidOperationException: 'VaryByQueryKeys' requires the response cache middleware.

Yes, I’m still rewriting an existing ASP.NET Web API application to ASP.NET Core.

I ported an existing action method where I was using response caching. I previously ported other action methods that used caching but this one was a little bit different because I had to take the querystring values into account for the caching.

This is easily arranged by specifying the name of the query string parameter using the VaryByQueryKeys property on the ResponseCache attribute.

Small tip: If you want to take all query string parameters into account, you can use “*” as a single value.

When I tried to call this method I got a 500 error. Inside the logs I noticed the following error message:

InvalidOperationException: 'VaryByQueryKeys' requires the response cache middleware.

Although caching seemed to work for other scenario’s, when I used the VaryByQueryKeys property I had to add the response caching middleware.

Here is my Startup.ConfigureServices():

And my Startup.Configure()