且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在ASP.NET中实现GZip压缩?

更新时间:2023-02-16 11:47:09

CSS文件,你实际上必须在IIS级别处理,因为这些文件是直接渲染的ASP.NET运行时。



你可以做一个JSX& CSSX扩展映射在IIS到aspnet_isapi.dll,然后利用你的邮政编码,但IIS可能会为你做一个更好的工作。



内容-encoding标头告诉浏览器它需要在渲染之前解压缩内容。有些浏览器很聪明,无论如何,基于内容的形状,但***只是告诉它。这是非常聪明的。



接受编码缓存设置是有因此缓存版本的gzip压缩内容将不会发送到只请求text / html的浏览器。


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!

Thanks

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.