Programmatically clear cache profile in asp.net core

4.6k Views Asked by At

I have setup a cache profile in my asp.net core web api as follows:

services.AddMvc(options => {
     // Cache profile for lookup data will expire every 15 minutes.
     options.CacheProfiles.Add("LookupData", new CacheProfile() { Duration = 15 });    
});

I have used this attribute at the top of my "lookupsController", as the lists of information returned in each method won't change regularly (although cache automatically expires every 15 minutes).

[ResponseCache(CacheProfileName = "LookupData")]
[Produces("application/json")]
[Route("api/Lookups")]
public class LookupsController : Controller
{
    ...
}

I have another admin controller which can allow users to add and remove items in the lookups controller list, this won't happen often but when it does, I want to programmatically force the cache profile to reset and force subsequent web requests to get the latest, rather than keeping the now outdated cached list of data.

How do I achieve the resetting of cache programmatically? - I can then add this code into my admin controller methods, to force cache resetting. Has anyone had to do this before?

1

There are 1 best solutions below

4
On BEST ANSWER

You cannot really clear that cache, because it's not server but client cache. ResponseCache attribute will just set certain headers in response. Simplified description of how this works: browser (or any intermediate proxy) making request to your api notice those response headers, sees that this response is valid for 15 minutes and so will not repeat that request for the next 15 minutes instead taking it from its local cache. Since you have no control over that local cache - you cannot clear it.