jbreuer/Hybrid-Framework-Best-Practices

Cache Can be Polluted by Preview Content

Opened this issue · 5 comments

Was just reviewing the GetVaryByCustomString in the Global: https://github.com/jbreuer/Hybrid-Framework-Best-Practices/blob/master/development/Umbraco.Extensions/Utilities/Global.cs

Doesn't look like it's taking into account that the user may be previewing the site. Doesn't that mean elements that are being previewed (i.e., potentially not yet published) may get cached and viewed by normal site visitors who are not in preview mode?

I ask because I've come across this issue in the past. Below is one way to solve it (though, I think there is a built-in Umbraco function you can use rather than looking at the cookie):

public override string GetVaryByCustomString(HttpContext context, string custom)
{
    custom = custom ?? string.Empty;
    if (custom.ToLower() == "Something".ToLower())
    {

        // Domain is included so requests cached per domain aren't shared.
        var fullUrl = new Uri(context.Request.Url, context.Request.RawUrl).AbsoluteUri;
        var key = GetKeyWithBuster(fullUrl);


        // Avoid contaminating the primary cache with Umbraco previews.
        try
        {
            var cookie = context.Request.Cookies["UMB_PREVIEW"];
            if (cookie != null && !string.IsNullOrWhiteSpace(cookie.Value))
            {
                key = key + "_PREVIEW_" + cookie.Value;
            }
        }
        catch { }


        // ... a few other key modifications removed...


        // Return cache key.
        return "something=" + fullUrl + " * key=" + key;

    }
    return base.GetVaryByCustomString(context, custom);
}

@Nicholas-Westby This is cool! Where is the GetKeyWithBuster method and what does it do?

@Jeavon Let me see if I can remember. It constructs a key that can be used to store pages by in the cache. If you publish a page, this key changes for the page that was published, so that the next request will have a new key (which will cause the cache to refresh). Basically, I couldn't figure out how to clear the cache, so I just create a new entry in the cache. As far as how it is implemented, I think I stored a dictionary with the key being the page ID and the value being a GUID. I'd update that dictionary on publish operations. And the method GetKeyWithBuster would use the GUID in that dictionary to construct the key.

By the way, I mentioned that preview mode can be detected with an Umbraco function. Here that is:

 UmbracoContext.Current.InPreviewMode

That's interesting, I've just done some very similar using a custom attribute, you can see here https://gist.github.com/Jeavon/be9f8ca38cf8996ffede

That looks neat. So, you decorate your action methods with [ConfigDurationOutputCache] and that bypasses caching during requests that occur while a user is previewing the site?

Yes exactly