I am trying to implement GZip compression for my asp.net page (including my CSS and JS files). I tried the following code, but it only compresses my .aspx page (found it from YSlow)
HttpContext context = HttpContext.Current; context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress); HttpContext.Current.Response.AppendHeader("Content-encoding", "gzip"); HttpContext.Current.Response.Cache.VaryByHeaders["Accept-encoding"] = true;
The above code is only compressing my .aspx page code (markup) not the CSS and JS files which is included as external files. Please tell me how can I implement GZip compression in ASP.NET using code (because I am on shared hosting server where I don't have access to IIS Server configurations). And also in the above code I am not getting the last two lines, why they are used and what's the purpose of these lines. Please explain!
When you're unable to use the compression features of web servers (IIS, Apache, Nginx), ASP.NET Core provides an alternate option, Response Compression middleware. It's performance won't match server based compression features though.
Here is the solution for css and javascript files. Add the following code to <system.webServer> inside your web.config file:
<configuration> ... <system.webserver> ... <httpCompression> <scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll"/> <dynamicTypes> <add mimeType="text/*" enabled="true"/> <add mimeType="message/*" enabled="true"/> <add mimeType="application/javascript" enabled="true"/> <add mimeType="*/*" enabled="false"/> </dynamicTypes> <staticTypes> <add mimeType="text/*" enabled="true"/> <add mimeType="message/*" enabled="true"/> <add mimeType="application/javascript" enabled="true"/> <add mimeType="*/*" enabled="false"/> </staticTypes> </httpCompression> <urlCompression doStaticCompression="true" doDynamicCompression="true"/> ... </system.webserver> ... <configuration>
Credit: How to GZip on ASP.NET and GoDaddy
For compressing JS & CSS files you actually have to handle that at the IIS level, since these files are rendered directly without the ASP.NET runtime.
You could make a JSX & CSSX extension mapping in IIS to the aspnet_isapi.dll and then take advantage of your zip code, but IIS is likely to do a better job of this for you.
The content-encoding header tells the browser that it needs to unzip the content before rendering. Some browsers are smart enough to figure this out anyway, based on the shape of the content, but it's better to just tell it.
The Accept-encoding cache setting is there so that a cached version of the gzipped content won't be sent to a browser that requested only text/html.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With