Asp.net MVC gzip压缩

启用gzip,deflate压缩可以减少相应的传输量,MVC可以通过自定义actionfilter实现

 

using System.IO; 
using System.IO.Compression;  
 
public  class EnableCompressionAttribute : ActionFilterAttribute 

     const CompressionMode compress = CompressionMode.Compress; 
     public  override  void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
        HttpRequestBase request = filterContext.HttpContext.Request; 
        HttpResponseBase response = filterContext.HttpContext.Response;  string acceptEncoding = request.Headers[ " Accept-Encoding "]; 
         if (acceptEncoding ==  null
             return
 
         if (acceptEncoding.ToLower().Contains( " gzip ")) 
        { 
            response.Filter =  new GZipStream(response.Filter, compress); 
            response.AppendHeader( " Content-Encoding "" gzip "); 
        } 
         else  if (acceptEncoding.ToLower().Contains( " deflate ")) 
        { 
            response.Filter =  new DeflateStream(response.Filter, compress); 
            response.AppendHeader( " Content-Encoding "" deflate "); 
        } 
    } 

 

 

你可能感兴趣的:(asp.net)