asp.net mvc compress stream and remove whitespace

前端 未结 2 1176
独厮守ぢ
独厮守ぢ 2021-02-01 10:15

So I am compressing my output stream via an action filter:

var response = filterContext.HttpContext.Response;
response.Filter = new DeflateStream(response.Filter         


        
相关标签:
2条回答
  • 2021-02-01 11:00

    I'm not seeing much wrong with the code above however you may want to try this approach:

    var response = filterContext.HttpContext.Response; 
    using(var wsf = new WhitespaceFilter(response.Filter))
    {
       wsf.Flush();
       response.Filter = new DefalteStream(wsf, CompressMode.Compress);
    }
    

    BTW are you using this attribute approach when applying the compressing and white space removal:

    http://www.avantprime.com/articles/view-article/7/compress-httpresponse-for-your-controller-actions-using-attributes

    DaTribe

    0 讨论(0)
  • 2021-02-01 11:03

    For those who get this far... you can do it... just swap the order of the stream chaining:

       public override void OnActionExecuting(ActionExecutingContext filterContext)
       {
            var response = filterContext.HttpContext.Response;
    
            // - COMPRESS
            HttpRequestBase request = filterContext.HttpContext.Request;
            string acceptEncoding = request.Headers["Accept-Encoding"];
            if (!String.IsNullOrEmpty(acceptEncoding))
            {
                acceptEncoding = acceptEncoding.ToUpperInvariant();
    
                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);
                }
            }
    
            // - REMOVE WHITE SPACE
            response.Filter = new WhitespaceFilter(response.Filter);
        }
    
    0 讨论(0)
提交回复
热议问题