15

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?

28

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
    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. – Matt Connolly Sep 22 '16 at 20:45
3

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 acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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