Search code examples
cachingasp.net-core-mvcvarybyquerykeys

VaryByQueryKeys not working with parameters


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)
        {

Solution

  • 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