1using System;
2using System.Web;
3using System.Web.Mvc;
4
5public class CacheFilterAttribute : ActionFilterAttribute
6{
7 /// <summary>
8 /// Gets or sets the cache duration in seconds. The default is 10 seconds.
9 /// </summary>
10 /// <value>The cache duration in seconds.</value>
11 public int Duration
12 {
13 get;
14 set;
15 }
16
17 public CacheFilterAttribute()
18 {
19 Duration = 10;
20 }
21
22 public override void OnActionExecuted(FilterExecutedContext filterContext)
23 {
24 if (Duration <= 0) return;
25
26 HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;
27 TimeSpan cacheDuration = TimeSpan.FromSeconds(Duration);
28
29 cache.SetCacheability(HttpCacheability.Public);
30 cache.SetExpires(DateTime.Now.Add(cacheDuration));
31 cache.SetMaxAge(cacheDuration);
32 cache.AppendCacheExtension("must-revalidate, proxy-revalidate");
33 }
34}