[英]How do I compress a Json result from ASP.NET MVC with IIS 7.5
我很難讓 IIS 7 正確壓縮來自 ASP.NET MVC 的 Json 結果。 我在 IIS 中啟用了靜態和動態壓縮。 我可以用 Fiddler 驗證普通文本/html 和類似的記錄被壓縮。 查看請求,存在接受編碼 gzip 標頭。 響應具有 MIME 類型“application/json”,但未壓縮。
我已經確定該問題似乎與 MimeType 相關。 當我包含mimeType="*/*"
,我可以看到響應已正確壓縮。 如何在不使用通配符 mimeType 的情況下讓 IIS 進行壓縮? 我認為這個問題與 ASP.NET MVC 生成內容類型標頭的方式有關。
CPU 使用率遠低於動態節流閾值。 當我檢查來自 IIS 的跟蹤日志時,我可以看到它由於找不到匹配的 mime 類型而無法壓縮。
<httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files" noCompressionForProxies="false">
<scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll" />
<dynamicTypes>
<add mimeType="text/*" enabled="true" />
<add mimeType="message/*" enabled="true" />
<add mimeType="application/x-javascript" enabled="true" />
<add mimeType="application/json" enabled="true" />
</dynamicTypes>
<staticTypes>
<add mimeType="text/*" enabled="true" />
<add mimeType="message/*" enabled="true" />
<add mimeType="application/x-javascript" enabled="true" />
<add mimeType="application/atom+xml" enabled="true" />
<add mimeType="application/xaml+xml" enabled="true" />
<add mimeType="application/json" enabled="true" />
</staticTypes>
</httpCompression>
確保您的%WinDir%\\System32\\inetsrv\\config\\applicationHost.config包含以下內容:
<system.webServer>
<urlCompression doDynamicCompression="true" />
<httpCompression>
<dynamicTypes>
<add mimeType="application/json" enabled="true" />
<add mimeType="application/json; charset=utf-8" enabled="true" />
</dynamicTypes>
</httpCompression>
</system.webServer>
來自@AtanasKorchev 的鏈接。
正如@simon_weaver 在評論中所說,您可能在 64 位 Windows 上使用 32 位編輯器編輯了錯誤的文件,請使用 notepad.exe 確保確實修改了此文件。
我已經成功地使用了這里強調的方法。
這些答案都不適合我。 我確實注意到了application/json; charset=utf-8 mime 類型。
我推薦這種方法
創建CompressAttribute
類,並設置目標操作。
ActionFilterAttribute 方法已針對 ASP.NET 4.x 更新並包含 Brotli.NET 包。
using System;
using System.IO.Compression;
using Brotli;
using System.Web;
using System.Web.Mvc;
public class CompressFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpRequestBase request = filterContext.HttpContext.Request;
string acceptEncoding = request.Headers["Accept-Encoding"];
if (string.IsNullOrEmpty(acceptEncoding)) return;
acceptEncoding = acceptEncoding.ToUpperInvariant();
HttpResponseBase response = filterContext.HttpContext.Response;
if (acceptEncoding.Contains("BR"))
{
response.AppendHeader("Content-encoding", "br");
response.Filter = new BrotliStream(response.Filter, CompressionMode.Compress);
}
else if (acceptEncoding.Contains("GZIP"))
{
response.AppendHeader("Content-encoding", "gzip");
response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
}
else if (acceptEncoding.Contains("DEFLATE"))
{
response.AppendHeader("Content-encoding", "deflate");
response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.