Last active
August 13, 2021 09:25
-
-
Save ErikHen/384904335c7235b47c938d1394e9c2b9 to your computer and use it in GitHub Desktop.
Episerver CMS editable cache attribute.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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