Skip to content

Instantly share code, notes, and snippets.

@ErikHen
Last active August 13, 2021 09:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ErikHen/384904335c7235b47c938d1394e9c2b9 to your computer and use it in GitHub Desktop.
Save ErikHen/384904335c7235b47c938d1394e9c2b9 to your computer and use it in GitHub Desktop.
Episerver CMS editable cache attribute.
namespace Demo
{
public class EditableCacheAttribute : ContentOutputCacheAttribute
{
public EditableCacheAttribute()
{
UseOutputCacheValidator = UseOutputCache;
}
private static bool UseOutputCache(IPrincipal principal, HttpContextBase context, TimeSpan duration)
{
var useOutputCache = false;
if (!principal.Identity.IsAuthenticated && duration != TimeSpan.Zero)
{
if (string.Equals(context.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
useOutputCache = true;
var url = context.Request.Url?.ToString();
var content = UrlResolver.Current.Route(new UrlBuilder(url)) as PageData;
var proxyCacheTime = new TimeSpan(0, 0, 600); //default time: 10 minutes
if (content is ICacheSettings cacheSettings)
{
useOutputCache = cacheSettings.DisableOutputCache != true; //check if output cache is disabled by editor
proxyCacheTime = cacheSettings.CdnCacheTime > 0 ? new TimeSpan(0, 0, cacheSettings.CdnCacheTime) : proxyCacheTime; //override cache time with editor setting
}
if (useOutputCache)
{
var eTag = content?.Saved.Ticks.ToString() ?? string.Empty;
context.Response.Cache.SetETag(eTag);
context.Response.Cache.SetProxyMaxAge(proxyCacheTime);
context.Response.Cache.SetMaxAge(proxyCacheTime);
}
}
}
return useOutputCache;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment