Take the community feedback survey now.

Custom Response Cache Attribute

Vote:
 

HI,

I have written code for Response Cache custom cache attribute and decorate in controller page wise.

Everything is working fine values of cache reflecting property in network cache-control. Like cache duration value is for Home page i set 60 sec. then i would expect till to 60 sec page should display from cache but it is not happening.

Can anyone suggest how can i test this functionality?

Custom cache attribute

{
    public enum CacheType
    {
        ProductPage,
        HomePage,
    }
 
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class CustomCacheAttribute : Attribute, IActionFilter
    {
        private readonly CacheType _cacheType;
        public CustomCacheAttribute(CacheType cacheType)
        {
            _cacheType = cacheType;
        }
       
        public void OnActionExecuted(ActionExecutedContext context)
        {
            var contentRepository = ServiceLocator.Current.GetInstance<IContentRepository>();
 
            var page = contentRepository
               .GetChildren<ConfigPageModel>(ContentReference.RootPage)
               .FirstOrDefault();
 
            if (page is not null)
            {
                int? duration = _cacheType switch
                {
                    CacheType.ProductPage => page.ProductPageCacheDuration,
                    CacheType.HomePage => page.HomePagePageCacheDuration,
                 };
 
                if (duration.HasValue && duration.Value > 0)
                {
                    var headers = context.HttpContext.Response.GetTypedHeaders();
                    headers.CacheControl = new Microsoft.Net.Http.Headers.CacheControlHeaderValue
                    {
                        Public = true,
                        MaxAge = TimeSpan.FromSeconds(duration.Value)
                    };
                    headers.Expires = DateTimeOffset.UtcNow.AddSeconds(duration.Value);
                    //  Location = ResponseCacheLocation.Any;
 
                    context.HttpContext.Response.Headers["Pragma"] = "cache";
                    context.HttpContext.Response.Headers["Vary"] = "Accept-Encoding";
                }
            }
 
        }
 
        public void OnActionExecuting(ActionExecutingContext context)
        {
 
        }
    }
}

Custorm Attribute Decorate in controller on index method

[CustomCache(CacheType.HomePage)]


Thanks,

Deepmala

#341056
Edited, Nov 21, 2025 12:15
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.