Sitecore - clears user cache programmatically

I have a custom role provider in which the role of a specific user can change when certain actions are performed.

This causes several problems:

  • If a user role is added, which allows them to access the page, this does not take effect until I clear the sitecore cache using /sitecore/admin/cache.aspx

  • We cache the display of the menu bar by the user. But when permissions change, new items can be added / items removed, but this is not reflected because it comes from the cached version.

Is there a way to programmatically clear a specific cache of a user's sitecore file?

+4
source share
1 answer

Yes - the way Sitecore does it by adding user data to the cache key for rendering. This storage is in the html cache, so to clear it you need to get the html cache and clear all entries containing the username.

This snippet will do this:

// 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 cacheKey = $"#login:True_#user:{Context.GetUserName()}";
htmlCache.RemoveKeysContaining(cacheKey);

This clears all entries in the html cache for the current user. If you want to clear for another user, just change Context.GetUserName()to get the specific user that you want to clear.

+5
source

All Articles