4

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Rob
  • 6,819
  • 17
  • 71
  • 131

1 Answers1

4

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.

Evk
  • 98,527
  • 8
  • 141
  • 191
  • Thanks very much for the info @Evk makes sense when you state it - I was hoping there was some sort of response header I could force onto any method that used that policy to force client to refresh but doesn't sound like it. I might have to mitigate the issue by reducing my cache timeout. – Rob Oct 23 '17 at 10:16
  • 1
    @RobMcCabe well response headers won't help anyway, because client (like browser) will just not call your api any more until cache time expires, so cannot evaluate any headers. – Evk Oct 23 '17 at 10:18
  • Thanks for the info Evk! – Rob Oct 23 '17 at 14:20
  • It might not have sense for existing users, but it would make sense to clear and regenerate the cache for the new users so that they would be able to get new data sooner. – To Ka Aug 04 '19 at 08:42