【问题标题】:How to support compressed HTTP requests in Asp.Net 4.0 / IIS7?如何在 Asp.Net 4.0 / IIS7 中支持压缩的 HTTP 请求?
【发布时间】:2011-05-23 14:19:05
【问题描述】:

对于 ASP.NET 4.0 / IIS7 Web 应用,我希望支持压缩的 HTTP 请求。基本上,我想支持在请求标头中添加Content-Encoding: gzip 并相应压缩正文的客户端。

有人知道我是如何实现这种行为的吗?

Ps:关于,我有多个端点 REST 和 SOAP,感觉更好的解决方案是支持 HTTP 级别的压缩,而不是每个端点的自定义编码器。

【问题讨论】:

    标签: asp.net iis request gzip http-compression


    【解决方案1】:

    虽然 hacky,但您可以使用原始的 Content-Length 绕过 WCF,即使在通过使用反射设置 HttpRequest 类中的私有 _contentLength 字段来解压缩请求之后。使用 Joannes Vermorel 的代码:

        void BeginRequest(object sender, EventArgs e)
        {
            var app = (HttpApplication)sender;
    
            if ("gzip" == app.Request.Headers["Content-Encoding"])
            {
                app.Request.Filter = new GZipStream(
                    app.Request.Filter, CompressionMode.Decompress);
    
                // set private _contentLength field with new content length after the request has been decompressed
                var contentLengthProperty = typeof(HttpRequest).GetField("_contentLength", BindingFlags.NonPublic | BindingFlags.Instance);
                contentLengthProperty.SetValue(app.Request, (Int32)app.Request.InputStream.Length);
            }
        }
    

    【讨论】:

      【解决方案2】:

      在这里尝试 Wiktor 对我的类似问题的回答:

      How do I enable GZIP compression for POST (upload) requests to a SOAP WebService on IIS 7?

      ...但请注意他在他的博客上的实现包含几个错误/兼容性问题,所以请尝试我在同一页面上发布的 HttpCompressionModule 类的修补版本。

      【讨论】:

        【解决方案3】:

        对于那些可能感兴趣的人,使用IHttpModule 来简单地过滤传入的请求,实现起来相当简单。

        public class GZipDecompressModule : IHttpModule
        {
            public void Init(HttpApplication context)
            {
                context.BeginRequest += BeginRequest;
            }
        
            void BeginRequest(object sender, EventArgs e)
            {
                var app = (HttpApplication)sender;
        
                if ("gzip" == app.Request.Headers["Content-Encoding"])
                {
                    app.Request.Filter = new GZipStream(
                       app.Request.Filter, CompressionMode.Decompress);
                }
            }
        
            public void Dispose()
            {
            }
        }
        

        更新:看来这种方法会在 WCF 中引发问题,因为 WCF 依赖于原始的 Content-Length,而不是解压缩后获得的值。

        【讨论】:

        • 我的印象是可以在 IIS 级别而不是在您的托管应用程序中配置压缩。不过我不太了解,只是建议google“IIS Compression”
        • 经典 HTTP 压缩仅适用于 responses,这就是我要压缩的 requests
        • 不,最后,我们决定重新实现我们自己的 HTTP 堆栈 :-(
        • @JoannesVermorel 在此处尝试 Wiktor 的解决方案:stackoverflow.com/questions/16671216/…(在我自己的答案中注明我的错误修正)。
        猜你喜欢
        • 1970-01-01
        • 2013-12-28
        • 2018-02-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-03
        相关资源
        最近更新 更多