WebApi Gzip(Deflate) 壓縮請求數據


由於不能直接訪問指定數據庫,只能通過跳板機查詢Oracle數據,所以要做一個數據中轉接口,

查詢數據就要壓縮,於是就找資料,代碼如下,其中要注意的是Response.Headers.Remove("Content-Encoding");

這段,對Response.Headrs的操作如果IIS6是不支持的,

會出現如下錯誤:

接口出現錯誤:"此操作要求使用 IIS 集成管線模式。" ()
System.PlatformNotSupportedException: 此操作要求使用 IIS 集成管線模式

 

其實在OnActionExecuting 這個方法中,請求中Content-Encoding本來就是空的,可以不必操作,

在項目中添加下面的類;

然后在Contoller方法上加上對應數據,即可實現對數據的壓縮。

 

// <summary>
    /// 自動識別客戶端是否支持壓縮,如果支持則返回壓縮后的數據
    /// Attribute that can be added to controller methods to force content
    /// to be GZip encoded if the client supports it
    /// </summary>
    public class CompressContentAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// Override to compress the content that is generated by
        /// an action method.
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(HttpActionContext filterContext)
        {
            GZipEncodePage();
        }

        /// <summary>
        /// Determines if GZip is supported
        /// </summary>
        /// <returns></returns>
        public static bool IsGZipSupported()
        {
            string AcceptEncoding = HttpContext.Current.Request.Headers["Accept-Encoding"];
            if (!string.IsNullOrEmpty(AcceptEncoding) &&
                    (AcceptEncoding.Contains("gzip") || AcceptEncoding.Contains("deflate")))
                return true;
            return false;
        }

        /// <summary>
        /// Sets up the current page or handler to use GZip through a Response.Filter
        /// IMPORTANT:
        /// You have to call this method before any output is generated!
        /// </summary>
        public static void GZipEncodePage()
        {
            HttpResponse Response = HttpContext.Current.Response;

            if (IsGZipSupported())
            {
                string AcceptEncoding = HttpContext.Current.Request.Headers["Accept-Encoding"];

                if (AcceptEncoding.Contains("deflate"))
                {
                    Response.Filter = new System.IO.Compression.DeflateStream(Response.Filter,
                                               System.IO.Compression.CompressionMode.Compress);
                    #region II6不支持此方法,(實際上此值默認為null 也不需要移除)
                    //Response.Headers.Remove("Content-Encoding");
                    #endregion
                    Response.AppendHeader("Content-Encoding", "deflate");
                }
                else
                {
                    Response.Filter = new System.IO.Compression.GZipStream(Response.Filter,
                                                 System.IO.Compression.CompressionMode.Compress);
                    #region II6不支持此方法,(實際上此值默認為null 也不需要移除)
                    //Response.Headers.Remove("Content-Encoding");
                    #endregion
                    Response.AppendHeader("Content-Encoding", "gzip");
                }
            }

            // Allow proxy servers to cache encoded and unencoded versions separately
            Response.AppendHeader("Vary", "Content-Encoding");
        }
    }

    /// <summary>
    /// 強制Defalte壓縮
    /// Content-encoding:gzip,Content-Type:application/json
    /// DEFLATE是一個無專利的壓縮算法,它可以實現無損數據壓縮,有眾多開源的實現算法。
    /// </summary>
    public class DeflateCompressionAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext filterContext)
        {
            HttpResponse Response = HttpContext.Current.Response;
            Response.Filter = new System.IO.Compression.DeflateStream(Response.Filter,
                                              System.IO.Compression.CompressionMode.Compress);
            #region II6不支持此方法,(實際上此值默認為null 也不需要移除)
            //Response.Headers.Remove("Content-Encoding");
            #endregion
            Response.AppendHeader("Content-Encoding", "deflate");
        }

        //public override void OnActionExecuted(HttpActionExecutedContext actContext)
        //{
        //    var content = actContext.Response.Content;
        //    var bytes = content == null ? null : content.ReadAsByteArrayAsync().Result;
        //    var zlibbedContent = bytes == null ? new byte[0] :
        //    APP.Core.Utility.ZHelper.DeflateByte(bytes);
        //    actContext.Response.Content = new ByteArrayContent(zlibbedContent);
        //    actContext.Response.Content.Headers.Remove("Content-Type");
        //    actContext.Response.Content.Headers.Add("Content-encoding", "deflate");
        //    actContext.Response.Content.Headers.Add("Content-Type", "application/json");
        //    base.OnActionExecuted(actContext);
        //}
    }

    /// <summary>
    /// 強制GZip壓縮,application/json
    /// Content-encoding:gzip,Content-Type:application/json
    /// GZIP是使用DEFLATE進行壓縮數據的另一個壓縮庫
    /// </summary>
    public class GZipCompressionAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext filterContext)
        {
            HttpResponse Response = HttpContext.Current.Response;
            Response.Filter = new System.IO.Compression.GZipStream(Response.Filter,
                                              System.IO.Compression.CompressionMode.Compress);
            #region II6不支持此方法,(實際上此值默認為null 也不需要移除)
            //Response.Headers.Remove("Content-Encoding");
            #endregion
            Response.AppendHeader("Content-Encoding", "gzip");
        }

        //public override void OnActionExecuted(HttpActionExecutedContext actContext)
        //{
        //    var content = actContext.Response.Content;
        //    var bytes = content == null ? null : content.ReadAsByteArrayAsync().Result;
        //    var zlibbedContent = bytes == null ? new byte[0] :
        //    APP.Core.Utility.ZHelper.GZipByte(bytes);
        //    actContext.Response.Content = new ByteArrayContent(zlibbedContent);
        //    actContext.Response.Content.Headers.Remove("Content-Type");
        //    actContext.Response.Content.Headers.Add("Content-encoding", "gzip");
        //    actContext.Response.Content.Headers.Add("Content-Type", "application/json");
        //    base.OnActionExecuted(actContext);
        //}
    }

 

使用方法

        [DeflateCompression]
        public string GetDeflate()
        {
            return "valuevaluevaluevaluevaluevaluevaluevaluevaluevalueSDFASDFASDFASDFASDFWERFWEFCASDFSDAFASDFASDFASDFSADFSA";
        }

        [CompressContent]
        public string GetGZip()
        {
            return "valuevaluevaluevaluevaluevaluevaluevaluevaluevalueSDFASDFASDFASDFASDFWERFWEFCASDFSDAFASDFASDFASDFSADFSA";
        }

        [GZipCompression]
        public string GetRaw()
        {
            return "valuevaluevaluevaluevaluevaluevaluevaluevaluevalueSDFASDFASDFASDFASDFWERFWEFCASDFSDAFASDFASDFASDFSADFSA";
        }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM