DEV Community

Cover image for Compressing the response of an .NET Core C# API 📦
Marcos Henrique
Marcos Henrique

Posted on

Compressing the response of an .NET Core C# API 📦

To make this improvement we will use the technique of data compression with the GZIP.

What is data compression? 🤔

Data compression is a way to use less space to store the most information, thus reducing the space used, which can be an image, text, video or any type of file. To reduce the space used, several algorithms are used to reduce the amount of bytes required to represent a given information.

What is GZIP? 😵

Gzip is a file format and software application used for file compression and decompression as a free software replacement for the compression program used on early Unix systems and intended for GNU.

Gzip is based on the DEFLATE algorithm, which is a combination of the coding LZ77 and Huffman.

DEFLATE it was designed as a replacement for LZW and other patent-overloaded data compression algorithms that at the time limited the usability of the compactor and other popular archivers.

After all, how do I compress WebAPI requests? 🤓

There are several ways to apply this compression, most of them through attributes in methods, I will show how to configure in one place so that all requests have the return already compressed, avoiding these attributes.

Follow these steps:
Step 1:

Install the package:

Microsoft.AspNet.WebApi.Extensions.Compression.Server
Enter fullscreen mode Exit fullscreen mode

Step 2:
Browse your solution to the App_Start folder then open the WebApiConfig.cs file, we will import two libs from the package we installed.

using Microsoft.AspNet.WebApi.Extensions.Compression.Server;  
using System.Net.Http.Extensions.Compression.Core.Compressors;
Enter fullscreen mode Exit fullscreen mode

Step3:

Finally at the end of the Register method the following line

config.MessageHandlers.Insert(0, new ServerCompressionHandler(new GZipCompressor(), new DeflateCompressor()));  
Enter fullscreen mode Exit fullscreen mode

Results🔬

After applying this technique, we had the following results:

  • 78% decrease in response size;

  • 4.3% decrease in waiting time for response;

Before gzip application:

After gzip application:

🎉🎊🎆

Referências 📚

Top comments (0)