How to Minify HTML using WebMarkupMin in ASP.NET Core
By FoxLearn 7/4/2024 9:25:42 AM 314
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%.
- Unable to resolve service for type 'Microsoft.AspNetCore.Identity.RoleManager'
- HTTP Error 500.30 ASP.NET Core app failed to start
- How to Use IExceptionHandler in ASP.NET Core
- How to custom exception handling in ASP.NET Core
- How to create a custom AuthorizeAttribute in ASP.NET Core
- How to manually resolve a type using the ASP.NET Core MVC
- Differences Between AddTransient, AddScoped, and AddSingleton
- How to add security headers to your ASP.NET Core