C# 如何在 ASP.NET 中实现 GZip 压缩?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/552317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to implement GZip compression in ASP.NET?
提问by Prashant
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)
我正在尝试为我的 asp.net 页面(包括我的 CSS 和 JS 文件)实现 GZip 压缩。我尝试了以下代码,但它只压缩了我的 .aspx 页面(从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!
上面的代码只是压缩我的 .aspx 页面代码(标记),而不是作为外部文件包含的 CSS 和 JS 文件。请告诉我如何使用代码在 ASP.NET 中实现 GZip 压缩(因为我在共享托管服务器上,我无法访问 IIS 服务器配置)。而且在上面的代码中,我没有得到最后两行,为什么使用它们以及这些行的目的是什么。请解释!
采纳答案by Ben Scheirman
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.
对于压缩 JS 和 CSS 文件,您实际上必须在 IIS 级别进行处理,因为这些文件是在没有 ASP.NET 运行时直接呈现的。
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.
您可以在 IIS 中将 JSX 和 CSSX 扩展映射到 aspnet_isapi.dll,然后利用您的邮政编码,但 IIS 可能会为您做得更好。
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.
Accept-encoding 缓存设置在那里,以便 gzip 内容的缓存版本不会发送到仅请求 text/html 的浏览器。
回答by gix
To answer your last question. Those two lines set HTTP headers for the response sent back to the browser. Content-Encoding
tells the browser that the response is encoded as gzip and it needs to be decoded. The last line adds Accept-Encoding
to the Vary header. With this the browser or proxies can determine whether the response was unique or is influenced by certain other headers and adjust their caching.
回答你的最后一个问题。这两行为发送回浏览器的响应设置 HTTP 标头。Content-Encoding
告诉浏览器响应被编码为 gzip 并且需要被解码。最后一行添加Accept-Encoding
到Vary 标头。有了这个,浏览器或代理可以确定响应是唯一的还是受某些其他标头的影响并调整它们的缓存。
回答by missaghi
In IIS7 all requests go to .net, so you would have to create an HttpModule that added those headers to all responses.
在 IIS7 中,所有请求都转到 .net,因此您必须创建一个 HttpModule,将这些标头添加到所有响应中。
Without IIS7, and on shared hosting, you would have to creare a handler that mapped a .net file extention that you are not using (like .asmx) and in the web.config specify that .asmx files go to your HttpHandler which is set to rewrite the path to .jpg or whatever and set the header there too.
如果没有 IIS7,并且在共享主机上,您必须创建一个处理程序来映射您不使用的 .net 文件扩展名(如 .asmx),并在 web.config 中指定 .asmx 文件转到您设置的 HttpHandler将路径重写为 .jpg 或其他格式,并在那里设置标题。
回答by intermension
The reason it's only compressing your ASPX file is that the code you have written is only embedded in the ASPX file. An ASPX file is a separate request from any linked content it contains. So if you have an ASPX page that contains:
它只压缩您的 ASPX 文件的原因是您编写的代码仅嵌入在 ASPX 文件中。ASPX 文件是与其包含的任何链接内容的单独请求。因此,如果您有一个包含以下内容的 ASPX 页面:
<img src="www.example.com\exampleimg.jpg" alt="example" />
This would amount to 2 requests (DNS lookups aside) from your browser to the resources:
这将相当于从您的浏览器到资源的 2 个请求(DNS 查找除外):
- for the aspx page and
- for the image contained by the aspx page.
- 对于 aspx 页面和
- 用于 aspx 页面包含的图像。
Each request has it own response steam. The code you have posted is attaching to the ASPX response stream only, which is why only your ASPX page is being compressed. Lines 1 & 2 of your posted code are essentially taking over the normal response stream of the page and injecting some "middle man" code that in this case eats and compresses the normal output stream with a GZip stream and sends that down the wire instead.
每个请求都有自己的响应流。您发布的代码仅附加到 ASPX 响应流,这就是为什么只有您的 ASPX 页面被压缩。您发布的代码的第 1 行和第 2 行基本上接管了页面的正常响应流并注入了一些“中间人”代码,在这种情况下,这些代码使用 GZip 流来处理和压缩正常输出流,然后将其发送到线路上。
Lines 3 & 4 are setting up the response headers. All http requests and responses have headers that are sent prior to the content. These set up the request/response so that the server and client know what is being sent and how.
第 3 行和第 4 行设置响应头。所有 http 请求和响应都具有在内容之前发送的标头。这些设置请求/响应,以便服务器和客户端知道正在发送什么以及如何发送。
In this case Line 3 is informing the client browser that the response stream is compressed via gzip and therefore needs to be de-compressed by the client browser prior to display.
在这种情况下,第 3 行通知客户端浏览器响应流是通过 gzip 压缩的,因此需要在显示之前由客户端浏览器解压缩。
And Line 4 is simply turning on the Accept-Encoding header of the response. This would otherwise have been absent from the response.
第 4 行只是打开响应的 Accept-Encoding 标头。否则,响应中将不存在这一点。
There are pluggable modules you can write/obtain that allow you to compress a multitide of other MIME type such as *.js and *.css but you're better off just using the built in compression functionality of IIS.
您可以编写/获取一些可插拔模块,这些模块允许您压缩其他 MIME 类型的多种类型,例如 *.js 和 *.css,但最好仅使用 IIS 的内置压缩功能。
You haven't said which verson of IIS you are using but if it were IIS 7.0, it would require that you include something like the following into the <system.webserver>
section of you web.config file:
您还没有说明您使用的是哪个版本的 IIS,但如果是 IIS 7.0,则需要您在<system.webserver>
web.config 文件的部分中包含以下内容:
<httpCompression>
<scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll" />
<staticTypes>
<add mimeType="text/*" enabled="true" />
</staticTypes>
</httpCompression>
<urlCompression doStaticCompression="true" />
..
..
Richard
理查德
回答by dortzur
Here is the solution for css and javascript files. Add the following code to inside your web.config file:
这是 css 和 javascript 文件的解决方案。将以下代码添加到您的 web.config 文件中:
<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"/>
回答by Nudier Mena
this may be useful for you try it out, this accepts deflate and gzip compression.
这可能对您尝试有用,它接受 deflate 和 gzip 压缩。
void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
string acceptEncoding = app.Request.Headers["Accept-Encoding"];
Stream prevUncompressedStream = app.Response.Filter;
if (app.Context.CurrentHandler == null)
return;
if (!(app.Context.CurrentHandler is System.Web.UI.Page ||
app.Context.CurrentHandler.GetType().Name == "SyncSessionlessHandler") ||
app.Request["HTTP_X_MICROSOFTAJAX"] != null)
return;
if (acceptEncoding == null || acceptEncoding.Length == 0)
return;
acceptEncoding = acceptEncoding.ToLower();
if (acceptEncoding.Contains("deflate") || acceptEncoding == "*")
{
// deflate
app.Response.Filter = new DeflateStream(prevUncompressedStream,
CompressionMode.Compress);
app.Response.AppendHeader("Content-Encoding", "deflate");
}
else if (acceptEncoding.Contains("gzip"))
{
// gzip
app.Response.Filter = new GZipStream(prevUncompressedStream,
CompressionMode.Compress);
app.Response.AppendHeader("Content-Encoding", "gzip");
}
}
回答by Chawathe Vipul S
Add .aspx extension to .css or .js file. Use <%@ Page ContentType="text/css" %> or javascript within the file to serve it with correct MIME type. & use URL Rewrite to hide this from the user agent browsers. The content-encoding response header is appended gzip to convey that gzip is the method used to perform compression. Vary response header's set to Accept-Encoding so all caches know which page (compressed or uncompressed) should be served depends on request's Accept-Encoding header. I've elaborated on this at https://stackoverflow.com/a/14509007/1624169
将 .aspx 扩展名添加到 .css 或 .js 文件。在文件中使用 <%@ Page ContentType="text/css" %> 或 javascript 以使用正确的 MIME 类型为其提供服务。& 使用 URL 重写从用户代理浏览器中隐藏它。内容编码响应标头附加 gzip 以表明 gzip 是用于执行压缩的方法。将响应标头设置为 Accept-Encoding 以便所有缓存都知道应该提供哪个页面(压缩或未压缩)取决于请求的 Accept-Encoding 标头。我在https://stackoverflow.com/a/14509007/1624169对此进行了详细说明
回答by Rick
You can just add the following to your web.config file within the <system.webServer>
element:
您只需将以下内容添加到<system.webServer>
元素内的 web.config 文件中:
<urlCompression doStaticCompression="true" doDynamicCompression="true" />
NOTE: If you are using an older version of IIS (less than v7.5), you may want to set doDynamicCompression to false because the process was CPU intensive. These issues were cleared up in IIS 7.5.
注意:如果您使用的是旧版本的 IIS(低于 v7.5),您可能需要将 doDynamicCompression 设置为 false,因为该进程是 CPU 密集型的。这些问题已在 IIS 7.5 中解决。
Reference: https://docs.microsoft.com/en-us/iis/configuration/system.webserver/urlcompression
参考:https: //docs.microsoft.com/en-us/iis/configuration/system.webserver/urlcompression
回答by JIYAUL MUSTAPHA
Either do it with the web.config file
要么使用 web.config 文件
<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>
Or you can do it through IIS. 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.
或者您可以通过 IIS 来完成。对于压缩 JS 和 CSS 文件,您实际上必须在 IIS 级别进行处理,因为这些文件是在没有 ASP.NET 运行时直接呈现的。
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.
您可以在 IIS 中将 JSX 和 CSSX 扩展映射到 aspnet_isapi.dll,然后利用您的邮政编码,但 IIS 可能会为您做得更好。
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.
Accept-encoding 缓存设置在那里,以便 gzip 内容的缓存版本不会发送到仅请求 text/html 的浏览器。