Asp.net MVC gzip压缩
启用gzip,deflate压缩可以减少相应的传输量,MVC可以通过自定义actionfilter实现
using System.IO;
using System.IO.Compression;
public class EnableCompressionAttribute : ActionFilterAttribute
{
const CompressionMode compress = CompressionMode.Compress;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpRequestBase request = filterContext.HttpContext.Request;
HttpResponseBase response = filterContext.HttpContext.Response; string acceptEncoding = request.Headers["Accept-Encoding"];
if (acceptEncoding == null)
return;
if (acceptEncoding.ToLower().Contains("gzip"))
{
response.Filter = new GZipStream(response.Filter, compress);
response.AppendHeader("Content-Encoding", "gzip");
}
else if (acceptEncoding.ToLower().Contains("deflate"))
{
response.Filter = new DeflateStream(response.Filter, compress);
response.AppendHeader("Content-Encoding", "deflate");
}
}
using System.IO.Compression;
public class EnableCompressionAttribute : ActionFilterAttribute
{
const CompressionMode compress = CompressionMode.Compress;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpRequestBase request = filterContext.HttpContext.Request;
HttpResponseBase response = filterContext.HttpContext.Response; string acceptEncoding = request.Headers["Accept-Encoding"];
if (acceptEncoding == null)
return;
if (acceptEncoding.ToLower().Contains("gzip"))
{
response.Filter = new GZipStream(response.Filter, compress);
response.AppendHeader("Content-Encoding", "gzip");
}
else if (acceptEncoding.ToLower().Contains("deflate"))
{
response.Filter = new DeflateStream(response.Filter, compress);
response.AppendHeader("Content-Encoding", "deflate");
}
}
}
posted on 2012-01-04 11:41 MoonWalker 阅读(702) 评论(0) 编辑 收藏 举报