I’ve been working with Nancy http://nancyfx.org/ for about a year, a great open-source project that I use primarily to add simple and low-overhead REST APIs to ASP.NET web forms projects.
Nancy routes that return HTML can benefit from minifying - a process which removes comments and whitespace, reducing the amount of data transmitted from server to the browser. To do the actual minifying, I used WebMarkupMin https://github.com/Taritsyn/WebMarkupMin which can be downloaded from NuGet at https://www.nuget.org/packages/WebMarkupMin.Core.
My minification code below assumes Nancy, WebMarkupMin & WebMarkupMin Web Extensions are installed in the project (including the relevant configuration in web.config) - follow directions on the respective sites to get them working in your environment. I developed the code in Visual Studio 2015 Update 2 on Windows with Nancy 1.4.2 and WebMarkupMin version 0.9.2.
Thomas’s “but it worked for me” disclaimer: before using any code you find on the internet, especially on this blog, take time to understand what the code does and test, test, test. I’m not responsible for damage caused by code from this blog, and don’t offer any support or warranty.
First I created a new class called “NancyBootstrapperEx” that inherits from DefaultNancyBootstrapper; if you already have a Nancy bootstrapper, you should be able to add the code in as you can only have one bootstrapper. From the Nancy docs at https://github.com/NancyFx/Nancy/wiki/Bootstrapper:
When the application starts up, Nancy looks for a custom bootstrapper. By default, it scans all assemblies with a reference to Nancy. If it doesn’t find one, it’ll fall back to the DefaultNancyBootstrapper. You can only have one bootstrapper per application. If more than one custom bootstrapper is found in your application, Nancy tries to be smart and checks if one inherits from the other. When that is the case Nancy chooses the most derived bootstrapper.
Based on Simon Cropp’s article “HTTP Compression with NancyFX” at http://simoncropp.com/httpcompressionwithnancyfx, I overrode the ApplicationStartup method to add an AfterRequest handler to check for HTML content, and minify. My language of choice is VB.NET, however the concept will work for C# too:
By dropping in my “NancyBootstrapperEx” class, any Nancy content returned as HTML will be minified and the code to return views from Nancy doesn’t need to be altered:
ReturnView("viewname",viewdata)
The code could probably be extended to compress HTML too. After experimenting with different browsers (cough IE11 cough) I made one further change, using Nancy’s fluent interface to add response headers telling the browser not to cache the returned view, like so: