Compression is a simple and effective way to reduce the size and responsiveness of response packets.
So how do I compress the ASP. I'll use a very popular library for compression/decompression called the dotnetzip library . This library can be obtained using NuGet packages
Now, we have implemented the deflate compression actionfilter.
Public classDeflatecompressionattribute:actionfilterattribute { Public Override voidonactionexecuted (Httpactionexecutedcontext actcontext) {varContent =actContext.Response.Content; varbytes = Content = =NULL?NULL: Content. Readasbytearrayasync (). Result; varzlibbedcontent = bytes = =NULL?New byte[0]: compressionhelper.deflatebyte (bytes); ActContext.Response.Content=Newbytearraycontent (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 classCompressionhelper { Public Static byte[] Deflatebyte (byte[] str) { if(str = =NULL) { return NULL; } using(varOutput =NewMemoryStream ()) { using ( varCompressor =NewIonic.Zlib.DeflateStream (output, Ionic.Zlib.CompressionMode.Compress, Ionic.zl Ib. Compressionlevel.bestspeed)) {compressor. Write (str,0, str. Length); } returnoutput. ToArray (); } } }
When using the
[deflatecompression] publicstring Get (int ID) { return " OK "+ID; }
Of course, if you use gzip compression, you only need to
New Ionic.Zlib.DeflateStream (instead
New Ionic.Zlib.GZipStream (, and then
ACTCONTEXT.RESPONSE.CONTENT.HEADERS.ADD ("content-encoding", "deflate");
ACTCONTEXT.RESPONSE.CONTENT.HEADERS.ADD ("content-encoding", "gzip");
Can, after I test,
Deflate compression is smaller than gzip-compressed code, so it is recommended to use deflate compression
Using gzip or deflate compression in the ASP. NET Web API