码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2014-10-07 00:36:01      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   使用   ar   sp   div   

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项目适配器开发实现缓存与压缩的重要机制

标签:style   blog   http   color   io   使用   ar   sp   div   

原文地址:http://www.cnblogs.com/weilai1917/p/4008757.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!