Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP NET Core - clear ResponseCache programmatically

I have a controller action which renders a partial view which fetches some data from the database asynchronously. Let's say these are menu items.

 [Route("SomeData")]
        [ResponseCache(Duration = 1000 * 60 * 60)]
        public IActionResult SomeData()
        {
            //returns a partial view for my ajax call
        }

The data does not change often, but a user might do something and know that it should result in a change in that partial view, i.e. new menu items should appear.

However, with a cached response, the data is not loaded from DB. I would like to add a 'refresh' button on the page so that a user can explicitly clear all cache.

I tried javascript to do window.reload(true); as well as this reply https://stackoverflow.com/a/55327928/2892378, but in both cases it does not work.

I need the behaviour identical to clicking Ctrl + Refresh button in Chrome.

Cheers

like image 813
Bartosz Avatar asked Sep 12 '25 10:09

Bartosz


1 Answers

That is cached on the client via headers in the response that you can't "clear" it . As a workaround , you can firstly setting a suited max age of the response cache on client side , then use VaryByHeader or VaryByQueryKeys , each time you want to refresh the cache you should provide a different value for your header/querystring :

https://learn.microsoft.com/en-us/aspnet/core/performance/caching/middleware?view=aspnetcore-3.1

like image 150
Nan Yu Avatar answered Sep 14 '25 01:09

Nan Yu