How to gzip svg files in ASP.NET

My previous post showed how to gzip svg files served by the Sitecore media library. This is fine if all svg files reside in the media library but this is typical not the case.

In this post I will show how to gzip compress any svg files served by your ASP.NET solution. As I explained in my previous post the issue that I am attempting to solve is that IIS will not by default gzip svg files without a lot of configuration changes on server level.

The solution here is extremely simple and pragmatic. Simply implement a HttpModule and set the Response.Filter stream to a GZipStream.

GZip svg files

  public class SvgCompressionModule : IHttpModule
  {
    public void Init(HttpApplication application)
    {
      application.BeginRequest += ApplicationOnBeginRequest;
    }

    public void Dispose()
    {
    }

    private void ApplicationOnBeginRequest(object sender, EventArgs eventArgs)
    {
      var app = (HttpApplication) sender;
      if (app == null)
        return;
      var context = app.Context;
      if (!IsSvgRequest(context.Request))
        return;
      context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
      context.Response.AddHeader("Content-encoding", "gzip");
    }

    protected virtual bool IsSvgRequest(HttpRequest request)
    {
      var path = request.Url.AbsolutePath;
      return Path.HasExtension(path) &&
             Path.GetExtension(path).Equals(".svg", StringComparison.InvariantCultureIgnoreCase);
    }
  }

Then add the httpmodule to configuration

<configuration>
  ...
  <system.webServer>
    <modules>
      ...
      <add name="SvgCompressionModule" type="[NAMESPACE].SvgCompressionModule, [ASSEMBLY].SvgCompression" />
    </modules>
  </system.webServer>
  ...
  <system.web>
    <httpModules>
      ...
      <add name="SvgCompressionModule" type="[NAMESPACE].SvgCompressionModule, [ASSEMBLY].SvgCompression" />
    </httpModules>
  </system.web>
</configuration>

That is it. I hope this helps someone out there in their own personal fight with Google PageSpeed.

 

 


Comments

6 responses to “How to gzip svg files in ASP.NET”

  1. Shafiq Avatar
    Shafiq

    I tried to implement gzip for font in so many ways but nothing worked. You solution worked like magic. Hats of man…genius better solution with full control.

    1. Thanks, I am glad you found it useful.

  2. Anders Hattestad Avatar
    Anders Hattestad

    Thank you for sharing.. Works like a charm

  3. This article is too helpful, thank you very much!!

  4. so as i understand it, this solution now makes the solution in the sitecore specific article reduntant? or is both required?

  5. Vinicius Watson Avatar
    Vinicius Watson

    Sir, you are my hero tonight… I was already screaming bloody murder

    Thank you