首页 > 代码库 > MVC项目适配器开发实现缓存与压缩的重要机制

MVC项目适配器开发实现缓存与压缩的重要机制

1、实现缓存保存在本地机制 缓存在开发高扩充性WEB程序的时候扮演着很重要的角色.我们可以将HTTP请求在一个定义的时间内缓存在用户的浏览器中,如果用户在定义的时间内请求同 一个URL,那么用户的请求将会从用户浏览器的缓存中加载,而不是从服务器.你可以在ASP.NET MVC应用程序中使用下面的Action Filter来实现同样的事情: 

 1 using System; using System.Web;  2 using System.Web.Mvc;  3 public class CacheFilterAttribute : ActionFilterAttribute { 4  /// /// Gets or sets the cache duration in seconds. The default is 10 seconds. 5  /// /// The cache duration in seconds.  6   public int Duration { get; set; }  7   public CacheFilterAttribute() { Duration = 10; }  8   public override void OnActionExecuted(FilterExecutedContext filterContext) {  9     if (Duration <= 0) 10         return; 11     HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache; 
      TimeSpan cacheDuration = TimeSpan.FromSeconds(Duration);
      cache.SetCacheability(HttpCacheability.Public);
      cache.SetExpires(DateTime.Now.Add(cacheDuration));
      cache.SetMaxAge(cacheDuration);
12     cache.AppendCacheExtension("must-revalidate, proxy-revalidate");
    }
  }

2、另外一个很重要的事情就是压缩.现在的浏览器都可以接收压缩后的内容,这可以节省大量的带宽.你可以在你的ASP.NET MVC 程序中应用下面的Action Filter 来压缩你的Response :

using System.Web; using System.Web.Mvc; public class CompressFilter : ActionFilterAttribute {   public override void OnActionExecuting(FilterExecutingContext filterContext)   {     HttpRequestBase request = filterContext.HttpContext.Request;     string acceptEncoding = request.Headers["Accept-Encoding"];     if (string.IsNullOrEmpty(acceptEncoding)) return;     acceptEncoding = acceptEncoding.ToUpperInvariant();    HttpResponseBase response = filterContext.HttpContext.Response;     if (acceptEncoding.Contains("GZIP"))     {       response.AppendHeader("Content-encoding", "gzip");       response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);     }     else if (acceptEncoding.Contains("DEFLATE"))     {       response.AppendHeader("Content-encoding", "deflate"); 
      response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);     }   }}

 

MVC项目适配器开发实现缓存与压缩的重要机制