Compression decompression of WEBAPI performance optimization

Source: Internet
Author: User
Tags httpcontext

Sometimes in order to improve WEBAPI performance and reduce response time, we use compression and decompression, while most client browsers now provide built-in decompression support. The larger the resources requested by the WEBAPI, the more noticeable the performance gains are with compression, and when the requested resource is very small, compression and decompression are not required because compression and decompression also take a certain amount of time.

See the Foreigner wrote an ASP. NET Web API GZip compression actionfilter with 8 lines of code

To tell the truth was attracted by this title, 8 lines of code to implement gzip compression filter, I followed his practice, found that incredibly Chinese garbled.

According to his way of realization:

1. Download Dotnetziplib Library

2. Add Ionic.Zlib.dll DLL Reference after decompression

3, the new deflatecompression features and gzipcompression features, respectively, representing deflate compression and gzip compression, the two compression methods are similar to the implementation code

A different place is

ACTCONTEXT.RESPONSE.CONTENT.HEADERS.ADD ("content-encoding", "gzip");

ACTCONTEXT.RESPONSE.CONTENT.HEADERS.ADD ("content-encoding", "deflate");

And

  var compressor = new Deflatestream (                    output, compressionmode.compress,                    compressionlevel.bestspeed)
var compressor = new GZipStream (                    output, compressionmode.compress,                    compressionlevel.bestspeed)
Using system.net.http;using system.web.http.filters;namespace webapi.filter{public class Gzipcompressionattribute:a            Ctionfilterattribute {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.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); }}}using system.net.http;using system.web.http.filters;namespace webapi.filter{public class DeflateCompressionAttr Ibute: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); }    }

4. Add a compression helper class Compressionhelper

Using system.io;using ionic.zlib;namespace webapi.filter{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, compressionlevel.bestspeed)) {compressor. Write (str, 0, str.                Length); } return output.            ToArray ();                }} public static byte[] Gzipbyte (byte[] str) {if (str = = null) {            return null;  } using (var output = new MemoryStream ()) {using (var compressor = new GZipStream (output, compressionmode.compress, CompressionleVel. Bestspeed)) {compressor. Write (str, 0, str.                Length); } return output.            ToArray (); }        }    }}

5, controller call, here I write the test code:

    public class Testcontroller:apicontroller    {        StringBuilder sb = new StringBuilder ();                [Gzipcompression]        public string Get (int id)        {for            (int i = 0; i < 1000;i++)            {                sb. Append ("Here is China's territory" + i);            }            Return SB. ToString () + DateTime.Now.ToLocalTime () + "," + ID;        }    }

The file size is 26.4kb and the request time is 1.27s, which is not using compression, comment//[gzipcompression] tag First

Using the [gzipcompression] tag, the file size is 2.4kb after adding compression, the response time is 1.21,respouse body is significantly smaller, but the response time is not obvious, because in the local environment download is too fast, and compression decompression to consume a certain amount of time, The interface loading time is mainly consumed on the onload. There is a problem: Chinese display garbled.

Using. Net-band compression, the corresponding class library--gzipstream and Deflatestream are provided in the System.IO.Compression. The controller call code does not change, create a new CompressContentAttribute.cs class, the code is as follows:

Using system.web;using system.web.http.controllers;using system.web.http.filters;namespace WebAPI.Filter{//<    Summary>////automatically identifies whether the client supports compression, and if so, returns the compressed data//Attribute that can is added to the controller methods to the Force content To be GZIP encoded if the client supports IT//</summary> public class Compresscontentattribute:acti        Onfilterattribute {//<summary>///compress the content that's generated by        An action method. </summary>//<param name= "Filtercontext" ></param> public override void Onactionexecu        Ting (Httpactioncontext filtercontext) {gzipencodepage (); }//<summary>//Determines if GZIP is supported///</summary>//<returns ></returns> public static bool Isgzipsupported () {String acceptencoding = httpcontext.c Urrent. 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:///before any output is generated! </summary> public static void Gzipencodepage () {HttpResponse Response = httpcontext.cu Rrent.            Response; if (isgzipsupported ()) {string acceptencoding = httpcontext.current.request.headers["Accept-enc                Oding "]; if (Acceptencoding.contains ("deflate")) {response.filter = new System.IO.Compression.De Flatestream (Response.filter, System.IO.Compression.CompressionMode.Compress)                    ; #region II6 does not support this method, (in fact this value defaults to null and does not need to be removed)//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 does not support this method, (in fact this value defaults to null and does not need to be removed)//response.headers.remove ("content-encoding");                #endregion Response.appendheader ("content-encoding", "gzip"); }}//allow proxy servers to cache encoded and unencoded versions separately Response.ap        Pendheader ("Vary", "content-encoding"); }}///<summary>//Mandatory defalte compression//Content-encoding:gzip,content-type:application/json//DEFLATE is a non-patented compression algorithm that enables lossless data compression,There are many implementations of open source algorithms. </summary> public class Deflatecompressionattribute:actionfilterattribute {public override void OnActionExecuting (Httpactioncontext filtercontext) {HttpResponse Response = HttpContext.Current.Respons            E Response.filter = new System.IO.Compression.DeflateStream (Response.filter, Sy Stem. Io.            Compression.CompressionMode.Compress);            #region II6 does not support this method, (in fact this value defaults to null and does not need to be removed)//response.headers.remove ("content-encoding");        #endregion Response.appendheader ("content-encoding", "deflate");    }}///<summary> forced gzip compression, Application/json///Content-encoding:gzip,content-type:application/json Gzip is another compression library that uses deflate to compress data///</summary> public class Gzipcompressionattribute:actionfilterattribut e {public override void OnActionExecuting (Httpactioncontext filtercontext) {HttpREsponse Response = HttpContext.Current.Response; Response.filter = new System.IO.Compression.GZipStream (Response.filter, Syste M.io.            Compression.CompressionMode.Compress);            #region II6 does not support this method, (in fact this value defaults to null and does not need to be removed)//response.headers.remove ("content-encoding");        #endregion Response.appendheader ("content-encoding", "gzip"); }    }}

Run view results, compression ability is slightly worse than Dotnetziplib, but no longer garbled.

Change the tag in the controller code to [Deflatecompression], and then look at the effect using deflate compression:

Deflate compression, content-length value is 2538, and gzip compression content-length value is 2556, visible deflate compression effect is better.

Here, WEBAPI compression I was implemented through the action filter, of course, you can also write in the WEBAPI in the global configuration, considering that some API interface does not need to use compression, so the action filter is implemented by the way.

Dudu This article httpclient with aps.net Web API: Compression and decompression of request content on client compression, decompression on the server.

Compression decompression of WEBAPI performance optimization

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.