1

我编写了一个 IHttpModule 使用 gzip 压缩我的响应(我返回大量数据)以减小响应大小。只要 Web 服务不引发异常,它就可以很好地工作。如果抛出异常,则会压缩异常,但 Content-encoding 标头会消失,并且客户端不知道读取异常。

我该如何解决这个问题?为什么标题不见了?我需要在客户端获取异常。

这是模块:

public class JsonCompressionModule : IHttpModule
{
    public JsonCompressionModule()
    {
    }

    public void Dispose()
    {
    }

    public void Init(HttpApplication app)
    {
        app.BeginRequest += new EventHandler(Compress);
    }

    private void Compress(object sender, EventArgs e)
    {
        HttpApplication app = (HttpApplication)sender;
        HttpRequest request = app.Request;
        HttpResponse response = app.Response;
        try
        {
            //Ajax Web Service request is always starts with application/json
            if (request.ContentType.ToLower(CultureInfo.InvariantCulture).StartsWith("application/json"))
            {
                //User may be using an older version of IE which does not support compression, so skip those
                if (!((request.Browser.IsBrowser("IE")) && (request.Browser.MajorVersion <= 6)))
                {
                    string acceptEncoding = request.Headers["Accept-Encoding"];

                    if (!string.IsNullOrEmpty(acceptEncoding))
                    {
                        acceptEncoding = acceptEncoding.ToLower(CultureInfo.InvariantCulture);

                        if (acceptEncoding.Contains("gzip"))
                        {
                            response.AddHeader("Content-encoding", "gzip");
                            response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
                        }
                        else if (acceptEncoding.Contains("deflate"))
                        {
                            response.AddHeader("Content-encoding", "deflate");
                            response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            int i = 4;
        }
    }
}

这是网络服务:

[WebMethod]
public void DoSomething()
{
    throw new Exception("This message get currupted on the client because the client doesn't know it gzipped.");
}

我感谢任何帮助。

谢谢!

4

1 回答 1

1

即使你发布这个问题已经有一段时间了,我也遇到了同样的问题,这就是我解决它的方法:

在 Init() 方法中,为 Error 事件添加一个处理程序

app.Error += new EventHandler(app_Error);

在处理程序中,从 Response 标头中删除 Content-Type 并将 Response.Filter 属性设置为 null。

void app_Error(object sender, EventArgs e)
{

    HttpApplication httpApp = (HttpApplication)sender;
    HttpContext ctx = HttpContext.Current;

    string encodingValue = httpApp.Response.Headers["Content-Encoding"];

    if (encodingValue == "gzip" || encodingValue == "deflate")
    {
        httpApp.Response.Headers.Remove("Content-Encoding");
        httpApp.Response.Filter = null;
    }

}

也许有一种更优雅的方法可以做到这一点,但对我有用。

于 2011-07-28T18:00:26.770 回答