当前位置: 移动技术网 > IT编程>开发语言>c# > mvc开启gzip压缩示例分享

mvc开启gzip压缩示例分享

2019年07月18日  | 移动技术网IT编程  | 我要评论
复制代码 代码如下:

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");
}
}
}
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网