How to Minify HTML using WebMarkupMin in ASP.NET Core

This post will show you how to Minify HTML using WebMarkupMin in ASP.NET Core MVC.

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 https://github.com/Taritsyn/WebMarkupMin

WebMarkupMin is a .NET library that contains a set of markup minifiers. The objective of this project is to improve the performance of web applications by reducing the size of HTML, XHTML and XML code.

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

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

Finally, add the required services to the IoC container. In the code below, I'm adding an HTML minifier and HTTP compression using GZIP.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    //Minify HTML
    services.AddWebMarkupMin(
        options =>
        {
            options.AllowMinificationInDevelopmentEnvironment = true;
            options.AllowCompressionInDevelopmentEnvironment = true;
        })
        .AddHtmlMinification(
            options =>
            {
                options.MinificationSettings.RemoveRedundantAttributes = true;
                options.MinificationSettings.RemoveHttpProtocolFromAttributes = true;
                options.MinificationSettings.RemoveHttpsProtocolFromAttributes = true;
            })
        .AddHttpCompression();
}

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%.