我試圖爲我正在處理的(asp.netwebforms)網站啓用gzip壓縮。我認爲我有一切工作,但是當我動態加載webresource.axd和scriptresource.axd文件時,它們通過壓縮來實現,因此頁面無法加載依賴於上述文件的內容或(調試時)無數javascript中斷的內容運行時異常,即;無效字符。ASP.NET,GZip和.AXD動態文件播放不好
這裏是我的Global.ascx.cs代碼的一部分,顯然是連接到PostReleaseRequestState事件。
void OnGlobalPostReleaseRequestState(object sender, EventArgs e)
{
string contentType = Response.ContentType;
// Compress only html, style-sheet, and javascript documents.
switch (contentType)
{
case "application/x-javascript":
case "text/javascript":
case "text/css":
case "text/html":
{
// Get the Accept-Encoding header value to know whether zipping is supported by the browser or not.
string acceptEncoding = Request.Headers["Accept-Encoding"];
if (string.IsNullOrEmpty(acceptEncoding)) return;
// If gzip is supported then gzip it else if deflate compression is supported then compress in that technique.
if (acceptEncoding.Contains("gzip"))
{
// Compress and set Content-Encoding header for the browser to indicate that the document is zipped.
Response.Filter = new GZipStream(Response.Filter, CompressionMode.Compress);
Response.AppendHeader("Content-Encoding", "gzip");
}
else if (acceptEncoding.Contains("deflate"))
{
// Compress and set Content-Encoding header for the browser to indicate that the document is zipped.
Response.Filter = new DeflateStream(Response.Filter, CompressionMode.Compress);
Response.AppendHeader("Content-Encoding", "deflate");
}
}
break;
}
}
和我的web.config與相關部分。
<!-- language-all: lang-xml -->
<staticContent>
<!-- Override IIS default, thus allowing JavaScript compression -->
<remove fileExtension=".js" />
<mimeMap fileExtension=".js" mimeType="text/javascript" />
</staticContent>
<httpCompression directory="%SystemDrive%\websites\_compressed" minFileSizeForComp="256">
<scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll" />
<staticTypes>
<add mimeType="text/*" enabled="true" />
<add mimeType="message/*" enabled="true" />
<add mimeType="application/javascript" enabled="true" />
<add mimeType="application/json" enabled="true" />
<add mimeType="*/*" enabled="false" />
</staticTypes>
<dynamicTypes>
<add mimeType="text/*" enabled="true" />
<add mimeType="message/*" enabled="true" />
<add mimeType="application/x-javascript" enabled="false" />
<add mimeType="*/*" enabled="false" />
</dynamicTypes>
</httpCompression>
<urlCompression doStaticCompression="true" doDynamicCompression="true" dynamicCompressionBeforeCache="false" />
<httpProtocol>
<customHeaders>
<add name="Content-Encoding" value="gzip" />
<add name="X-UA-Compatible" value="IE=9" />
</customHeaders>
</httpProtocol>
我需要禁用(* .axd)壓縮,或強制它在客戶端解壓縮。請幫助...
這是我完全一樣的問題。啓用gzip後,ScriptResource響應被雙重壓縮。您的解決方案很好。 – rocketsarefast
@DavidPine無論是.css還是.axd,我都發現無法提供gzip壓縮資源。更令人沮喪的是,當我查看IIS壓縮文件夾時,我看到壓縮的文件,但在響應頭文件中沒有接觸編碼:GZip。在你的代碼中,你正在手動添加這個頭......爲什麼? IIS不會自動執行該操作嗎? AND,上面是您的GlobalAsax代碼需要啓用壓縮的AXD資源,即你不能通過web.config – Jacques
@Jacques,我真的不記得。這是很久以前的事了,細節已經逃離了我的回憶。我建議你把這個問題作爲一個新問題,並且隨時在你的新問題中引用這個Q/A。對不起,我無法提供更多幫助。 –