asp.net mvc compress stream and remove whitespace

心已入冬 提交于 2019-12-02 18:34:36

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);
    }

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!