mvc开启gzip压缩示例分享_C#教程-查字典教程网
mvc开启gzip压缩示例分享
mvc开启gzip压缩示例分享
发布时间:2016-12-28 来源:查字典编辑
摘要:复制代码代码如下:usingSystem.IO;usingSystem.IO.Compression;usingSystem.Web;usi...

复制代码 代码如下:

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

}

}

}

}

相关阅读
推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
  • 大家都在看
  • 小编推荐
  • 猜你喜欢
  • 最新C#教程学习
    热门C#教程学习
    编程开发子分类