VaryByQueryKeys not working with parameters

842 Views Asked by At

My asp.net core mvc app doesn't always rerun the controller when I change the value of my parameter. It just returns the previous cache. I thought VaryByQueryKeys was meant to address this.

[ResponseCache(Duration = 3600, VaryByQueryKeys = new string[] { "widthHeight" }, Location = ResponseCacheLocation.Any)]
        [Route("/{widthHeight}")]
        public IActionResult Index(string widthHeight)
        {
2

There are 2 best solutions below

0
On BEST ANSWER

As far as I know, if you use chrome by entering the URL (e.g. www.example.com/abcd/index.html) directly into the address bar or use F5 to refresh the page, the chrome will always send the Cache-Control: max-age=0 header.

This is the reason why your response cache is not working.

To solve this issue, you should use another browser to test like IE11 or you could set a hyperlink in your application like below:

<a href="https://localhost:44374/?widthHeight=aaaa">aaa</a>

If you click this hyperlink, you will find the cache will work.

Result:

enter image description here

0
On

I encountered the same issue, none of the followings produce the expected cached-by-unique-parameters-values:

VaryByQueryKeys = new[] { "*" }

VaryByQueryKeys = new[] { "searchparam" }

given public async Task<IActionResult> Search([FromQuery] string searchparam)

Solution is prefix it with a $, that is VaryByQueryKeys = new[] { "$searchparam" }