简体   繁体   English

无需访问服务器配置即可对asp.net mvc 2进行GZip或Deflate压缩

[英]GZip or Deflate compression for asp.net mvc 2 without access to server config

I tried to use the method described here ASP.NET MVC Action Filter - Caching and Compression . 我试图使用这里描述的方法ASP.NET MVC Action Filter - Caching and Compression At first the results where encouraging as indeed the server started sending GZip encoded files but after further testing, at times, in pages with Html.RenderAction parts the attribute would get called twice gziping the allready gzipped page. 起初,结果令人鼓舞,因为服务器确实开始发送GZip编码文件,但经过进一步测试后,有时在带有Html.RenderAction部分的页面中,该属性将被调用两次gziping allready gzip压缩页面。 Does anyone know a more stable method of serving compressed pages with ASP.NET MVC 2 or any ideas of how to modify the code to be more general? 有没有人知道一个更稳定的方法来使用ASP.NET MVC 2提供压缩页面,或者任何关于如何修改代码的想法更通用?

public class CompressFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(FilterExecutingContext filterContext)
    {
        HttpRequestBase request = filterContext.HttpContext.Request;
        string acceptEncoding = request.Headers["Accept-Encoding"];
        if (string.IsNullOrEmpty(acceptEncoding)) return;
        acceptEncoding = acceptEncoding.ToUpperInvariant();
        HttpResponseBase response = filterContext.HttpContext.Response;
        if (acceptEncoding.Contains("GZIP"))
        {
            response.AppendHeader("Content-encoding", "gzip");
            response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
        }
        else if (acceptEncoding.Contains("DEFLATE"))
        {
            response.AppendHeader("Content-encoding", "deflate");
            response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
        }
    }

} }

You could ignore child actions: 您可以忽略子操作:

if (filterContext.IsChildAction)
{
    return;
}
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM