不得不说的wepapi 优化

1:在你的ASP.NET Web API中使用GZIP 或 Deflate 。
对于减少响应包的大小和响应速度,压缩是一种简单而有效的方式。
这是一个非常有必要使用的功能,你可以查看更多关于压缩的文章在我的博客 http://blog.developers.ba/asp-net-web-api-gzip-compression-actionfilter/

本人是在dll抽出源代码使用的功能。

原dll code:

1:新建过滤器(面向切面编程aop)

Code:

        public class DeflateCompressionAttribute : ActionFilterAttribute
        {
            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] :
                CompressionHelper.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);
            }
        }
 public class CompressionHelper
        {
            public static byte[] DeflateByte(byte[] str)
            {
                if (str == null)
                {
                    return null;
                }

                using (var output = new MemoryStream())
                {
                    using (var compressor = new DeflateStream(output, CompressionMode.Compress, true))
                    {
                        compressor.Write(str, 0, str.Length);
                    }

                    return output.ToArray();
                }
            }
        }

使用:以特性的方式在想要压缩的webapi方法以[xxx]方式添加。

运行结果:

 

解压code:

 class Program
    {
        static void Main(string[] args)
        {
            string sss = HttpGet("http://localhost:16808//api/GPSStatus/GetListHis?i=1&flag=0&pageIndex=1&pageSize=10", true);

        }

        public static string HttpGet(string url, object par = null, bool IsGZip = false)
        {
            WebRequest request = null;
            WebResponse response = null;
            try
            {
                //创建请求  
                request = HttpWebRequest.Create(url);
                request.Method = "GET";
                request.ContentType = "application/json";
                request.Credentials = CredentialCache.DefaultCredentials;
                request.Timeout = 60000;
                response = request.GetResponse();
                string result = null;
                if (IsGZip)
                {
                    using (var stream = response.GetResponseStream())
                    {
                        byte[] bytes = new byte[response.ContentLength];
                        stream.Read(bytes, 0, bytes.Length);
                        result = UnJy(bytes);
                    }
                }
                else
                {
                    using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                        result = sr.ReadToEnd();
                }
                return result;
            }
            catch (Exception)
            {
                return null;
            }
            finally
            {
                if (response != null) response.Close();
                if (request != null) request.Abort();
            }
        }


        /// <summary>
        /// 解压
        /// </summary>
        public static string UnJy(byte[] by)
        {
            using (MemoryStream stream = new MemoryStream(by))
            {
                Stream decompressor = new DeflateStream(stream, CompressionMode.Decompress);
                return UncompressString(by, decompressor);
            }
        }

        private static string UncompressString(byte[] compressed, Stream decompressor)
        {
            byte[] buffer = new byte[0x400];
            Encoding encoding = Encoding.UTF8;
            using (MemoryStream stream = new MemoryStream())
            {
                using (decompressor)
                {
                    int num;
                    while ((num = decompressor.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        stream.Write(buffer, 0, num);
                    }
                }
                stream.Seek(0L, SeekOrigin.Begin);
                StreamReader reader = new StreamReader(stream, encoding);
                return reader.ReadToEnd();
            }
        }


        public class CompressionHelper
        {
            public static byte[] DeflateByte(byte[] str)
            {
                if (str == null)
                {
                    return null;
                }

                using (var output = new MemoryStream())
                {
                    using (var compressor = new DeflateStream(output, CompressionMode.Compress,true))
                    {
                        compressor.Write(str, 0, str.Length);
                    }

                    return output.ToArray();
                }
            }
        }
    }

当然你也可以使用文章开头的链接直接附加Dll 

其他的优化。

http://www.oschina.net/translate/8-ways-improve-asp-net-web-api-performance

posted @ 2016-01-15 16:03  s_p  阅读(446)  评论(0编辑  收藏  举报