How to enable response compression in ASP.Net Core
Enable both Gzip and Brotli compression.
Brotli compression has better performance when dealing HTML, CSS and JS files. you can enable it in the Startup.cs file.
// response compression
services.AddResponseCompression(options =>
{
options.Providers.Add<BrotliCompressionProvider>();
options.Providers.Add<GzipCompressionProvider>();
// support custom mimetypes
options.MimeTypes =
ResponseCompressionDefaults.MimeTypes.Concat(
new[] { "image/svg+xml" });
});
services.Configure<BrotliCompressionProviderOptions>(options =>
{
options.Level = (CompressionLevel)4; // 4 or 5 is OK
});
Default Response Compression Mime Types
public static readonly IEnumerable<string> MimeTypes = new[]
{
// General
"text/plain",
// Static files
"text/css",
"application/javascript",
"text/javascript",
// MVC
"text/html",
"application/xml",
"text/xml",
"application/json",
"text/json",
// WebAssembly
"application/wasm",
};
Use Response Compression
app.UseResponseCompression() in the Configure method needs to be before app.UseStaticFiles() as otherwise headers have already been sent.
app.UseResponseCompression();
Setting Brotli compression level when using response compression in ASP.NET Core