16

We have an action that updates some user profile information that is displayed in components that are cached with a vary by user setting. Is there a way to clear the cache for only that one user?

2 Answers 2

29

You can do this by making sure that your renderings are set to Vary by User. This adds the user to the cacheKey string like this "_#user:" + Context.GetUserName();

You can then use the following code to clear the html cache for that user:

// Need to clear the cache for the header and the user profile....
var htmlCache = CacheManager.GetHtmlCache(Context.Site);

// Remove all cache keys that contain the currently logged in user.
var cacheKeyPart = $"_#login:True_#user:{Context.GetUserName()}";
htmlCache.RemoveKeysContaining(cacheKeyPart);

For more detailed information have a look at this post: http://www.sitecorenutsbolts.net/2016/04/26/Advanced-Cache-Clearing/

1
  • 1
    This was super helpful, thanks! One tweak I made was to adjust my cacheKeyPart to be only $"_#user:{Sitecore.Context.GetUserName()}" since we were not using the vary by logged in setting. Sep 22, 2016 at 20:45
4

This depends on how often does the data change and what triggers the change.

One possible option would be to use additionally vary by query string option which will cache the output for the user and specific value of query string. This way every time the user changes their query (thus changing query string) the ouput will be rendered from scratch.

On the other hand if the data changes often it might be worth considerig turning off the cache at all(for this particular rendering).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.