Steoates
Steoates

Reputation: 3168

JSON Compression attribute

I have been using a compression attribute I found on the web, which is working very well for us.

  public override void OnActionExecuting(ActionExecutingContext 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);
        }
    }

the problem I have is that when an exception is thrown, then the screen displays the compressed content (I think!).. it looks like this..

xi��V�4��^ :b���$I"i#!c{��`$c��'wy�N�������H:��38�YS�b?ߕ�!`WSϙ��萧̬n��H����:V(ylZ� �ωԱ��Ϟӱ=�囥�ֺ���V��/>�^R���$٣����T�����J�oRݬz���?6$�<��KՔ��B0�x��V$�����F�h+Ǐ���!���0J��ɒ�h��+VR�p�ۊ�������!��-cccs�Z�%��2{�Ѿ��r�����۩/�,�n��n�f���tܳu�}����.+t��]���̆�����,�c��-�H0)J������dP�� ��   ��/�|��#�Z�]O

My question is, is it possible to somehow work around this? Any way I can get this action to work nicely with exceptions?

Upvotes: 1

Views: 349

Answers (1)

volpav
volpav

Reputation: 5128

You can remove the compression filter in Application_Error:

protected void Application_Error(object sender, EventArgs e)
{
  (sender as HttpApplication).Response.Filter = null;
}

Alternatively, you can try updating the Content-Encoding response header appropriately but I haven't tried that so not sure if it's going to work.

Upvotes: 1

Related Questions