2

I want OutputCache attribute to produce a header with Cache-Control set to public. How do I do that?

1 Answer 1

2

Maybe this code for Attribute will help

using System;
using System.Web;
using System.Web.Mvc;

    public class CacheFilterAttribute : ActionFilterAttribute {
        /// <summary>
        /// Gets or sets the cache duration in seconds. The default is 10 seconds.
        /// </summary>
        /// <value>The cache duration in seconds.</value>
        public int Duration {
            get;
            set;
        }

        public CacheFilterAttribute() {
            Duration = 30;
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext) {
            if (Duration <= 0) return;

            HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;
            TimeSpan cacheDuration = TimeSpan.FromSeconds(Duration);

            cache.SetCacheability(HttpCacheability.Public);
            cache.SetExpires(DateTime.Now.Add(cacheDuration));
            cache.SetMaxAge(cacheDuration);
            cache.AppendCacheExtension("must-revalidate, proxy-revalidate");
        }
    }

and then use [CacheFilter] instead of OutputCache

Sign up to request clarification or add additional context in comments.

3 Comments

one important thing OutputCache filter does - is actually caching the response (server side), will this attribute cache the response (so that Action is not executed on every call)?
Hi try [CacheFilter(Duration = 60, Order = 2)] [OutputCache(Duration = 60, Order = 1)]
Gets or sets the cache duration in seconds. The default is 10 seconds. public CacheFilterAttribute() { Duration = 30; }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.