PROWAREtech

articles » current » asp-net-core » enable-output-compression

ASP.NET Core: Enable Output Compression

How to enable site-wide compression for HTTP and HTTPS; written in C#.

These examples use .NET Core 3.1, .NET 6 and .NET 8.

Easily enable response compression for an ASP.NET Core Web Application.

Modify the Program.cs file as has been done with this snippet of code (see comments).

using Microsoft.AspNetCore.ResponseCompression;

var builder = WebApplication.CreateBuilder(args);

// ...

builder.Services.AddResponseCompression(options =>
{
    options.Providers.Add<BrotliCompressionProvider>();
    options.Providers.Add<GzipCompressionProvider>();
	// NOTE: could also add the DeflateCompressionProvider here
    options.EnableForHttps = true; // NOTE: compress over HTTPS, too
    options.MimeTypes = new string[] { "image/svg+xml", "application/pdf", "application/json", "application/javascript", "application/rtf", "application/xhtml+xml", "application/xml", "text/*", "model/gltf+json" }; // NOTE: add MIME-Types to compress here
});

builder.Services.Configure<BrotliCompressionProviderOptions>(options =>
{
    options.Level = CompressionLevel.Optimal; // NOTE: this takes longer to compress but it is not as aggressive as the Optimal setting when using the compression classes directly
});

builder.Services.Configure<GzipCompressionProviderOptions>(options =>
{
    options.Level = CompressionLevel.Optimal;
});

// ...

var app = builder.Build();
app.UseResponseCompression(); // NOTE: call this soon after the line of "var app = builder.Build();"

// ...

USE THIS UTILITY TO TEST THE HTTP COMPRESSION.

Modify the Startup.cs file. Under the ConfigureServices() method, add the BrotliCompressionProvider and set the compression level to Optimal which is a balance between compression speed and compression ratio. Finally, add the middleware app.UseResponseCompression() BEFORE the other middleware components.

// Startup.cs
using System.IO.Compression;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace ProjectName
{
	public class Startup
	{
		public Startup(IConfiguration configuration)
		{
			Configuration = configuration;
		}

		public IConfiguration Configuration { get; }

		// This method gets called by the runtime. Use this method to add services to the container.
		public void ConfigureServices(IServiceCollection services)
		{
			services.AddControllersWithViews();
			services.AddResponseCompression(options =>
			{
				options.Providers.Add<BrotliCompressionProvider>();
				options.Providers.Add<GzipCompressionProvider>();
				options.EnableForHttps = true; // OPTIONAL - enable for sites that use HTTPS
				options.MimeTypes = new string[] { "image/svg+xml", "application/*", "text/*" }; // this should compress what needs to be compressed
			});
			services.Configure<BrotliCompressionProviderOptions>(options =>
			{
				options.Level = CompressionLevel.Optimal; // OPTIMAL is just that, not too fast or slow - this may or may not fit all websites' needs
			});
		}

		// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
		public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
		{
			app.UseResponseCompression(); // call this before app.UseStaticFiles(); and other middleware
			if (env.IsDevelopment())
			{
				app.UseDeveloperExceptionPage();
			}
			else
			{
				app.UseExceptionHandler("/Home/Error");
			}

			app.UseStaticFiles();

			app.UseRouting();

			app.UseAuthorization();

			app.UseEndpoints(endpoints =>
			{
				endpoints.MapControllerRoute(
					name: "default",
					pattern: "{controller=Home}/{action=Index}/{id?}");
			});
		}
	}
}

USE THIS UTILITY TO TEST THE HTTP COMPRESSION.

Coding Video

https://youtu.be/ZGvkLK8JrGo


This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
CLOSE