PROWARE technologies
PROWARE technologies

How to Enable ASP.NET Core MVC Website-wide Compression

This article requires ASP.NET Core 3.0.

Easily enable compression to an ASP.NET Core MVC Web Application.

Modify the Startup.cs file. Under the ConfigureServices() method, add the GzipCompressionProvider 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<GzipCompressionProvider>();
				//options.EnableForHttps = true; // OPTIONAL - enable for sites that use HTTPS
			});
			services.Configure<GzipCompressionProviderOptions>(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