How to Minify HTML using WebMarkupMin in ASP.NET Core
By FoxLearn 7/4/2024 9:25:42 AM 426
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 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.UseStaticFiles(); app.UseWebMarkupMin();//Minify content app.UseMvc(routes => { routes.MapRoute( 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) { services.AddMvc(); // Add WebMarkupMin services for HTML and other minification services.AddWebMarkupMin( options => { options.AllowMinificationInDevelopmentEnvironment = true; options.AllowCompressionInDevelopmentEnvironment = true; }) .AddHtmlMinification( options => { options.MinificationSettings.RemoveRedundantAttributes = true; options.MinificationSettings.RemoveHttpProtocolFromAttributes = true; options.MinificationSettings.RemoveHttpsProtocolFromAttributes = true; }) .AddHttpCompression(); }
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%.
- How to use CORS in ASP.NET Core
- How to Send Emails in ASP.NET Core
- How to Run Background Tasks in ASP.NET Core with Hosted Services
- Implementing Scheduled Background Tasks in ASP.NET Core with IHostedService
- Creating an Web API in ASP.NET Core
- 8 Essential Tips to Protect Your ASP.NET Core Application from Cyber Threats
- Implementing Caching in ASP.NET Core
- Building a Custom Request Pipeline with ASP.NET Core Middleware