Does anybody know how to enable gzip compression in MVC 3? I'm using IIS7.
Google Chrome Audit's result:
- Enable gzip compression (4)
- Compressing the following resources with gzip could reduce their transfer size by about two thirds (~92.23KB):
- /mydomain/ could save ~1.53KB
- jquery-1.4.4.min.js could save ~51.35KB
- Cufon.js could save ~11.89KB
- Futura.js could save ~27.46KB
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:
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:
optionalfeatures
(this is the quickest way to get to the "Turn Windows Features on or off" window) 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);
}
}
}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.