Build your own middleware - HTML Minification middleware
July 13, 2015 by Anuraj
.Net ASP.Net ASP.Net MVC Visual Studio
Minification refers to the process of removing unnecessary or redundant data without affecting how the resource is processed by the browser - e.g. code comments and formatting, removing unused code, using shorter variable and function names, and so on. If you are using wordpress, you will get some plugins which will help you to minify HTML and other static files like CSS, Javascript. ASP.NET MVC comes with bundling and minification feature which will help you to minify CSS and Javascript. This post is about a HTML Minification middleware, which will help developers to remove the whitespace in the generated HTML content.
How it works - Last post was about building a basic middleware. In this implementation, I am reading the content which will be writing back to response, removes whitespace between tags using Regular expressions and the whitespace removed stream I will be writing back to the response.
Here is the code snippet.
And here is the extension method which helps to inject the middleware to the pipeline.
Here is the test results before applying the middleware and after applying middleware. The middleware applied to the MusicStore application.
Without HtmlMinification middleware.
With HtmlMinification middleware.
Without middleware the document took almost 14.67 KB. With the HTML minification middleware it got reduced to 10.04 KB. You can find source code in GitHub. I will be adding the tests for the middleware soon.
Happy Programming :)
Copyright © 2024 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub