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 class Deflatecompressionattribute:actionfilterattribute {public override void onactionexecuted (httpact Ionexecutedcontext 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 Ionic.Zlib.DeflateStre AM (output, Ionic.Zlib.CompressionMode.Compress, Ionic.Zlib.CompressionLevel.BestSpe ed)) {Compressor. Write (str, 0, str. Length); } return output. ToArray (); } } }
When using the
[Deflatecompression] public string 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