5

I want to zipping response in my Asp.Net web site. and I wrote this code:

public static void CompressPage(HttpRequest Request, HttpResponse Response)
{
    string acceptEncoding = Request.Headers["Accept-Encoding"];
    Stream prevUncompressedStream = Response.Filter;

    if (acceptEncoding.IsEmpty())
    {
        return;
    }

    acceptEncoding = acceptEncoding.ToLower();

    if (acceptEncoding.Contains("gzip"))
    {
        Response.Filter = new GZipStream(prevUncompressedStream, CompressionMode.Compress);
        Response.AppendHeader("Content-Encoding", "gzip");
    }
    else if (acceptEncoding.Contains("deflate"))
    {
        Response.Filter = new DeflateStream(prevUncompressedStream, CompressionMode.Compress);
            Response.AppendHeader("Content-Encoding", "deflate");
    }
}

and call it it Page_Load event:

protected void Page_Load(object sender, EventArgs e)
{
    ...
    ZipHtmlPage.CompressPage(Request, Response);
}

The problem is when I run the code with and without above code in Page_Load the size of response does not change.

enter image description here

Where is the problem?

Thanks


Edit 1)

I think that "Content-Encoding", "gzip" doesn't add to header:

enter image description here

I don't know why?


Edit 2)

When I use HttpModule for doing http compression:

public class CompressModule : IHttpModule
{
    public void Init(HttpApplication application)
    {
        application.BeginRequest += (new EventHandler(this.Application_BeginRequest));
    }

    private void Application_BeginRequest(Object source, EventArgs e)
    {
        HttpContext context = HttpContext.Current;
        context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
        HttpContext.Current.Response.AppendHeader("Content-Encoding", "gzip"); 
    }
    public void Dispose()
    {
    }
}

I got this in every pages:

enter image description here

Arian
  • 12,793
  • 66
  • 176
  • 300
  • Googling for `asp.net enable gzip` has a number of possible ideas to try. Have you tried any of them? – mjwills Jun 30 '19 at 04:15
  • @mjwills I don't wnat to do that with `IIS`. I want to do compression for a few pages – Arian Jun 30 '19 at 04:24
  • 4
    Would recommend to do it on IIS level rather than building your own middleware. – Artyom Ignatovich Jul 03 '19 at 16:13
  • 1
    Yes I strongly agree with @ArtemIgnatovich , re-inventing the wheel is not the order of the day , it is not recommended to implement your own when we can leverage the feature provided in the the WebServer. – Soumen Mukherjee Jul 06 '19 at 18:42

3 Answers3

1

do you add these codes to your web.config file (for css and javascript files):

<system.webServer>
    <httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files">
      <scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll" staticCompressionLevel="9" />
      <dynamicTypes>
        <add mimeType="text/*" enabled="true" />
        <add mimeType="message/*" enabled="true" />
        <add mimeType="application/x-javascript" enabled="true" />
        <add mimeType="application/json" enabled="true" />
        <add mimeType="*/*" enabled="false" />
      </dynamicTypes>
      <staticTypes>
        <add mimeType="text/*" enabled="true" />
        <add mimeType="message/*" enabled="true" />
        <add mimeType="application/x-javascript" enabled="true" />
        <add mimeType="application/atom+xml" enabled="true" />
        <add mimeType="application/xaml+xml" enabled="true" />
        <add mimeType="*/*" enabled="false" />
      </staticTypes>
    </httpCompression>
...

maybe this link help you How to implement GZip compression in ASP.NET?

Masoud Sadeghi
  • 357
  • 3
  • 15
1

I think it's non-standard how you are adding your compression. What I've done in the past is configured GZip in the startup file. What else I've noticed is the compression didn't take effect in debug mode. Try deploying or running your app in release mode to see if it compresses the response.

In my configure services method of startup I have this:

services.Configure<GzipCompressionProviderOptions>(options =>
{
    options.Level = CompressionLevel.Optimal;
});
Paul Story
  • 582
  • 4
  • 10
0

This is not the correct way to compress pages like this, first, you need to check if the browser accepts gzip or deflate then start compressing it, that's why you are seeing wired characters.

private void Application_BeginRequest(Object source, EventArgs e)
{
    // wrong and dangerous
    HttpContext context = HttpContext.Current;
    context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
    HttpContext.Current.Response.AppendHeader("Content-Encoding", "gzip"); 
}

The better way:

void context_BeginRequest(object sender, EventArgs e)
{
    var app = (HttpApplication)sender;
    var encodings = app.Request.Headers.Get("Accept-Encoding");


    if (encodings == null)
        return;

    var baseStream = app.Response.Filter;


    // check if browser accepts gzip or deflate
    if (encodings.ToLower().Contains("gzip"))
    {
        app.Response.Filter = new GZipStream(baseStream, CompressionMode.Compress);
        app.Response.AppendHeader("Content-Encoding", "gzip");
        app.Context.Trace.Warn("GZIP compression on");
    }
    else if (encodings.ToLower().Contains("deflate"))
    {
        app.Response.Filter = new DeflateStream(baseStream, CompressionMode.Compress);
        app.Response.AppendHeader("Content-Encoding", "deflate");
        app.Context.Trace.Warn("Deflate compression on");
    }
}

I recommend using a library called HttpCompress, you can access it here. And again as other people said why don't you use built-in IIS compression module?

Ali Bahrami
  • 5,935
  • 3
  • 34
  • 53