在asp.net mvc3中扩展ActionFilterAttribute实现Http Cache Header修改
ActionFilterAttribute 是 System.Web.Mvc.ActionFilterAttribute
来自于:System.Web.Mvc.dll
#region Assembly System.Web.Mvc.dll, v4.0.30319 // C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 3\Assemblies\System.Web.Mvc.dll #endregion using System; namespace System.Web.Mvc { // Summary: // Represents the base class for filter attributes. [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)] public abstract class ActionFilterAttribute : FilterAttribute, IActionFilter, IResultFilter { // Summary: // Initializes a new instance of the System.Web.Mvc.ActionFilterAttribute class. protected ActionFilterAttribute(); // Summary: // Called by the ASP.NET MVC framework after the action method executes. // // Parameters: // filterContext: // The filter context. public virtual void OnActionExecuted(ActionExecutedContext filterContext); // // Summary: // Called by the ASP.NET MVC framework before the action method executes. // // Parameters: // filterContext: // The filter context. public virtual void OnActionExecuting(ActionExecutingContext filterContext); // // Summary: // Called by the ASP.NET MVC framework after the action result executes. // // Parameters: // filterContext: // The filter context. public virtual void OnResultExecuted(ResultExecutedContext filterContext); // // Summary: // Called by the ASP.NET MVC framework before the action result executes. // // Parameters: // filterContext: // The filter context. public virtual void OnResultExecuting(ResultExecutingContext filterContext); } }
以上是ActionFilterAttribute 类的具体代码,它是抽象类 abstract ,有四个虚方法 virtual .
User Story:
作为一个用户, 希望系统可以让我在需要访问系统时能够有快的速度, 以便我能够看到信息,提高我的体验。
为系统添加缓存:
给http header添加缓存值,使用其它缓存系统对web进行缓存,使用合适的缓存策略。
Cache-Control:max-age=value
E-TTL=value
1.扩展ActionFilterAttribute
CacheHeaderFilter
using System; using System.Web; using System.Web.Mvc; /// <summary> /// The cache filter. /// </summary> public class CacheHeaderFilter : ActionFilterAttribute { /// <summary> /// ETTL /// </summary> public int ETTL { get; set; } /// <summary> /// CacheControlMaxAge /// </summary> public int CacheControlMaxAge { get; set; } /// <summary> /// OnActionExecuted /// </summary> /// <param name="filterContext"></param> public override void OnActionExecuted(ActionExecutedContext filterContext) { var response = filterContext.HttpContext.Response; response.Cache.SetCacheability(HttpCacheability.Public); response.Cache.SetMaxAge(TimeSpan.FromSeconds(this.CacheControlMaxAge)); response.Headers.Add("E-TTL", this.ETTL.ToString()); }
在Asp.net MVC 中使用 CacheHeaderFilter
/// <summary> /// index page /// </summary> /// <returns></returns> [CacheHeaderFilter(CacheControlMaxAge = 3600, ETTL = 3600)] public ActionResult Index() { return View(); }