4
votes

I have a custom role provider, whereby the role for a particular user can change when they perform certain actions.

This is causing a couple of problems:

  1. If a role is added to a user, which would allow them access to a page, this doesn't take effect until I clear the sitecore cache manually using /sitecore/admin/cache.aspx

  2. We are caching a menu bar rendering by user. But when permissions change, new items may be added / items removed, but this isn't reflected because its coming from the cached version.

Is there a way I can programmatically clear a particular user's sitecore cache?

1

1 Answers

5
votes

Yes - the way Sitecore does this is by adding the user details to the cache key for a rendering. This is store in the html cache, so to clear it you need to get the html cache and clear all entries that contain the user name.

This snippet will do that:

// 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);

That clears all entries in the html cache for the currently logged in user. If you want to clear for a different user, just change the Context.GetUserName() to get the specific user you want to clear for.