[英]How to support compressed HTTP requests in Asp.Net 4.0 / IIS7?
对于ASP.NET 4.0 / IIS7 Web应用程序,我想支持压缩的HTTP 请求 。 基本上,我想支持在请求标头中添加Content-Encoding: gzip
客户端,并相应地压缩主体。
有谁知道我是如何实现这样的行为的?
Ps:关于,我有多个端点REST和SOAP,它感觉更好的解决方案来支持HTTP级别的压缩,而不是每个端点的自定义编码器。
对于那些可能感兴趣的人来说, 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
而不是解压缩后获得的值。
在这里尝试Wiktor对我类似问题的回答:
如何为IIS 7上的SOAP WebService的POST(上载)请求启用GZIP压缩?
...但请注意他在博客上的实现包含一些错误/兼容性问题,所以请尝试在同一页面上发布的HttpCompressionModule类的修补版本。
虽然hacky,但是即使在解压缩请求之后,您也可以使用反射通过在HttpRequest
类中设置private _contentLength
字段来使用原始Content-Length
来绕过WCF。 使用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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.