mvc开启gzip压缩示例分享
程序员文章站
2023-12-19 23:19:46
复制代码 代码如下:using system.io;using system.io.compression;using system.web;using system.we...
复制代码 代码如下:
using system.io;
using system.io.compression;
using system.web;
using system.web.mvc;
public class compressattribute : actionfilterattribute
{
public override void onresultexecuted(resultexecutedcontext filtercontext)
{
//如果出现错误,则不进行压缩,否则页面会出现乱码,而不是报错的黄页
if (filtercontext.exception != null)
return;
httpresponsebase response = filtercontext.httpcontext.response as httpresponsebase;
//判断iis或者其他承载设备是是否启用了gzip或deflatestream
if (response.filter is gzipstream || response.filter is deflatestream)
return;
//开始进入压缩环节
string acceptencoding = filtercontext.httpcontext.request.headers["accept-encoding"];
if (!string.isnullorempty(acceptencoding) && (acceptencoding.contains("gzip") || acceptencoding.contains("deflate")))
{
if (acceptencoding.contains("gzip"))
{
response.filter = new gzipstream(response.filter, compressionmode.compress);
response.headers.remove("content-encoding");
response.appendheader("content-encoding", "gzip");
}
else
{
response.filter = new deflatestream(response.filter, compressionmode.compress);
response.headers.remove("content-encoding");
response.appendheader("content-encoding", "deflate");
}
}
}
}