How to Enable ASP.NET Core Website-wide Compression

This article requires ASP.NET Core 3.1.

This will not compress dynamic content over an HTTPS connection. See related articles: Compress HTTPS Blazor WASM WebAPI Output and Compress HTTPS .NET Core WebAPI Output

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

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.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 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?}");
			});
		}
	}
}

Coding Video

https://youtu.be/ZGvkLK8JrGo


Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site.
OK