在 IIS7上使用 MVC3时如何启用 gzip 压缩?

有人知道如何在 MVC3中启用 gzip 压缩吗? 我正在使用 IIS7。

谷歌 Chrome 审计结果:

  1. 启用 gzip 压缩(4)
  2. 使用 gzip 压缩以下资源可以将它们的传输大小减少三分之二(~ 92.23 KB) :
  3. /mydomain/可以节省 ~ 1.53 KB
  4. Jquery-1.4.4. min.js 可以节省 ~ 51.35 KB
  5. Js 可以节省11.89 KB
  6. Futura.js 可以节省约27.46 KB
55174 次浏览

Compression is enabled/disabled at the server's level. See IIS compression module in iis management console.

Here are the instructions for IIS from microsoft site.

You can configure compression through your web.config file as follows:

<system.webServer>
<urlCompression doStaticCompression="true" doDynamicCompression="true" />
</system.webServer>

You can find documentation of this configuration element at iis.net/ConfigReference. This is the equivalent of:

  1. Opening Internet Information Services (IIS Manager)
  2. Navigating through the tree-view on the left until you reach the virtual directory you wish to modify
  3. Selecting the appropriate virtual directory so that the title of the right-hand pane becomes the name of said virtual directory.
  4. Choosing "Compression" under "IIS" in the right-hand pane
  5. Ticking both options and choosing "Apply" under "Actions" on the far right.

Note: (As pointed out in the comments) You need to ensure that Http Dynamic Compression is installed otherwise setting doDynamicCompression="true" will not have any effect. The quickest way to do this is:

  1. Start > Type optionalfeatures (this is the quickest way to get to the "Turn Windows Features on or off" window)
  2. Navigate to Internet Information Services > World Wide Web Services > Performance Features in the "Windows Features" treeview
  3. Ensure "Dynamic Content Compression" is ticked
  4. Click "Ok" and wait whilst Windows installs the component

You could do this in code if you rather do that. I would make a basecontroller which every control inherits from and decorate it with this attribute below.

public class CompressAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{


var encodingsAccepted = filterContext.HttpContext.Request.Headers["Accept-Encoding"];
if (string.IsNullOrEmpty(encodingsAccepted)) return;


encodingsAccepted = encodingsAccepted.ToLowerInvariant();
var response = filterContext.HttpContext.Response;


if (encodingsAccepted.Contains("deflate"))
{
response.AppendHeader("Content-encoding", "deflate");
response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
}
else if (encodingsAccepted.Contains("gzip"))
{
response.AppendHeader("Content-encoding", "gzip");
response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
}
}
}