Compressing A Single ASP.NET Response Manually
This post is about compressing your HTTP result without using IIS Dynamic Compression. I’ll save the story to the end and give you the code first:
Well, this shows how to do the compression itself. Depending on how you do ASP.NET, you probably will call it differently.
In my case, I called it manually from an ASP.NET Webforms PageMethod (more on why below), but if you are using ASP.NET MVC for example, you probably want to wrap it in an ActionFilter and apply that to the action you want to compress its output. Let me know in the comments or on twitter if you have a problem implementing it in a particular situation.
IIS Dynamic Compression
IIS 7+ has built in dynamic compression support (compressing output of server-side scripts like ASP.NET, PHP, etc.). It’s not by default because compressing dynamic content means running the compression for every request (because it doesn’t know what the server-side script will generate for every request, the point of using server-side programming is generating dynamic content!).
Static compression on the other side (caching static files like styles and scripts) is on by default because once the static resource is compressed, the compressed version is cached and served for every future request of the same file (unless the file changes of course).
General advice: I’d say if your server side scripts expect to return large text-based content (say, large data, even after paging, etc. like large reports or whatever), always turn dynamic compression on, at least for the pages that expect to return large data sets of text.
In many cases though the majority of large files will be scripts (and possibly images) will be the larger parts though, which are often taken care of (for scripts for example) by IIS static compression or ASP.NET Bundling.
How did I learn that?
As a bonus for coming here, I'm giving away a free newsletter for web developers that you can sign up for from here.
It's not an anything-and-everything link list. It's thoughtfully collected picks of articles and tools, that focus on Angular 2+, ASP.NET (4.x/MVC5 and Core), and other fullstack developer goodies.
Take it for a test ride, and you may unsubscribe any time.
You might also want to support me by checking these out [Thanks]: