Pre-compressed static files with ASP.NET Core

Optimizing web applications is important because more economic web applications consume less CPU cycles and need less bandwidth – resources we have to pay for. It’s easy to turn on response compression on ASP.NET Core, but serving pre-compressed files needs more work. This blog post shows how to do it.

Why pre-compressed files?

Although it’s possible to compress files dynamically when files are requested from server it means additional work for web server. Files to be compressed are changed only when new deployment of application is made. And the better compression we want the more work has CPU to do.

This fact makes us ask a question: is it possible to serve these files without compressing them over and over again? Fortunately, answer to this question is positive – yes, we can do it in ASP.NET Core by extending static files middleware a little bit.

Creating pre-compressing files

To keep things simple while working on solution we can use 7-Zip to compress static files on disk. Here’s the example of 7-Zip dialog window when compressing site.css file of default ASP.NET Core MVC application.

Using maximum gzip compression with 7-Zip

Notice how I turned on very strong compression (ultra level). This is certainly something that we don’t want to do at web server dynamically.

To compress static files during build it’s possible to use gzip() task in gulp based bundling and minification. I don’t stop on this topic in this post.

Serving pre-compressed files

During my little research I found simple solution from Stack Overflow thread How to gzip static content in ASP.NET Core in a self host environment. It handles Javascript and CSS files.

app.UseStaticFiles(new StaticFileOptions
{
    OnPrepareResponse = context =>
    {
        IHeaderDictionary headers = context.Context.Response.Headers;
        string contentType = headers["Content-Type"];
        if (contentType == "application/x-gzip")
        {
            if (context.File.Name.EndsWith("js.gz"))
            {
                contentType = "application/javascript";
            }
            else if (context.File.Name.EndsWith("css.gz"))
            {
                contentType = "text/css";
            }
            headers.Add("Content-Encoding", "gzip");
            headers["Content-Type"] = contentType;
        }
    }
});

As Javascript and CSS are not the only file types that can be pre-compressed I looked for solution to detect MIME-type from file name or extension and found the writing Getting A Mime Type From A File Name In .NET Core from .NET Core Tutorials site. Their solution seemed neat and simple to me.

var provider = new FileExtensionContentTypeProvider();
string contentType;
if (!provider.TryGetContentType(fileName, out contentType))
{
    contentType = "application/octet-stream";
}

I mixed these two samples together and got the following working solution.

var mimeTypeProvider = new FileExtensionContentTypeProvider();

app.UseStaticFiles(new StaticFileOptions
{
    OnPrepareResponse = context =>
    {
        var headers = context.Context.Response.Headers;
        var contentType = headers["Content-Type"];

        if (contentType != "application/x-gzip" && !context.File.Name.EndsWith(".gz"))
        {
            return;
        }

        var fileNameToTry = context.File.Name.Substring(0, context.File.Name.Length - 3);

        if (mimeTypeProvider.TryGetContentType(fileNameToTry, out var mimeType))
        {
            headers.Add("Content-Encoding", "gzip");
            headers["Content-Type"] = mimeType;
        }
    }
});

With this piece of code my challenge was completed  for now. Those who want to use ready-made package can use compressed static files middleware by Peter Andersson.

Wrapping up

Although using pre-compressed files is not mainstream in web development it still can save us CPU cycles and bandwidth. Compressing of static files can be one step in ASP.NET Core application build. Although pre-compressed files are not supported by ASP.NET Core out-of-box it was still very easy to extend static files middleware to make it support pre-compressed files.

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    Leave a Reply

    Your email address will not be published. Required fields are marked *