How to Minify HTML using WebMarkupMin in ASP.NET Core

By FoxLearn 7/4/2024 9:25:42 AM   118
Minifying HTML in ASP.NET Core MVC using WebMarkupMin involves a few steps.

Minification is a performance optimization, it's designed to reduce the amount of data being transferred over the network.

You need to install WebMarkupMin.AspNetCore1 library from NuGet Package Manager or download it directly from

WebMarkupMin is a .NET library that can be integrated into your ASP.NET Core MVC project to minify HTML, CSS, and JavaScript. The objective of this project is to improve the performance of web applications by reducing the size of HTML, XHTML and XML code.

Here’s how to Minify HTML using WebMarkupMin in ASP.NET Core

Use WebMarkupMin Middleware

Open your Startup class, then add a configuration to minify the HTML as below

public void Configure(IApplicationBuilder app)
    app.UseWebMarkupMin();//Minify content
    app.UseMvc(routes =>
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");

This middleware ensures that all HTML responses are minified before being sent to the client.

Configure WebMarkupMin in Startup.cs

Open your Startup.cs file and locate the ConfigureServices method. Add the following code to configure WebMarkupMin services:

public void ConfigureServices(IServiceCollection services)
    // Add WebMarkupMin services for HTML and other minification
        options =>
            options.AllowMinificationInDevelopmentEnvironment = true;
            options.AllowCompressionInDevelopmentEnvironment = true;
            options =>
                options.MinificationSettings.RemoveRedundantAttributes = true;
                options.MinificationSettings.RemoveHttpProtocolFromAttributes = true;
                options.MinificationSettings.RemoveHttpsProtocolFromAttributes = true;

In the code above, I'm adding an HTML minifier and HTTP compression using GZIP.

After configuring WebMarkupMin, run your ASP.NET Core MVC application. View the HTML source of your pages in a browser (use Developer Tools to inspect the network response to see the minified HTML).

As you can see, adding the HTML minification and compression at runtime has a latency cost that is relatively important when you add minification, but this loss is also compensated for by reducing size the amount of data transfer, reducing the total download time by 80%.