How to bust the cache or obtain cache key when using <distributed-cache> Tag helper in Asp.net Core MVC

404 views Asked by At

Having an issue with the <distributed-cache> tag and Redis.

We have a <partial> Razor view that displays results of a long-running query. We acquire the data from a service injected in using @inject. The data updates very rarely, hence we wrap the content in a <distributed-cache> tag helper, with a long expires-after attribute.

However, when the data is finally updated (in another part of our app), we need to delete that key from the distributed cache, in order to force the page to update on next execution. (It's not possible for us to predict when the data will change - we can only respond to an external event.)

The problem we're having is that, despite having a fixed name attribute, the cache key appears to be impossible to predict. For example <distributed-cache name='_myQuery' vary-by-user='true'> creates a key something along the lines 7/za/Bc/ZRn/MsR/hG69TYTx1LEzqBvlyH1OLJgrpk4= in Redis.

How can I either:

  1. Predict/calculate what the cache key is going to be in redis, so that I can delete it in another part of our application?;

  2. Force the <distributed-cache> tag to ignore the cached value this one time? I know we have the enabled property, because this isn't going to work because the page doesn't know when to invalidate the cache.

1

There are 1 answers

0
SimonGoldstone On

After digging into the ASP.NET Core source I've found the CacheTagKey.cs file, which contains the GenerateKey() and GenerateHaskedKey() methods. These methods create the key from a bunch of params, then SHA256 hashes the key and returns base64.

So it looks like I can use this to predict the cache key and solve the issue.