DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • GDPR Compliance With .NET: Securing Data the Right Way
  • How to Enhance the Performance of .NET Core Applications for Large Responses
  • Developing Minimal APIs Quickly With Open Source ASP.NET Core
  • Revolutionizing Content Management

Trending

  • How to Submit a Post to DZone
  • From "Vibe Coding" to Production: Setting Up an Evals Loop for Claude Agents
  • DZone's Article Submission Guidelines
  • Why Your AI Agent's Logs Aren't Earning Trust
  1. DZone
  2. Coding
  3. Frameworks
  4. Serving Pre-Compressed Static Files in ASP.NET Core

Serving Pre-Compressed Static Files in ASP.NET Core

Web apps could always use more optimization. We take a look at how to optimize the serving of static files.

By 
Gunnar Peipman user avatar
Gunnar Peipman
·
Mar. 08, 19 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
11.2K Views

Join the DZone community and get the full member experience.

Join For Free

Optimizing web applications is important because more economic web applications consume fewer 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 a server it means additional work for the web server. Files to be compressed are changed only when a new deployment of the 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, the answer to this question is positive — yes, we can do it with ASP.NET Core by extending static files' middleware a little bit.

Creating Pre-compressing Files

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

7-Zip

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

To compress static files during the build, it's possible to use gzip() task in Gulp-based bundling and minification (though I won't cover this topic in this post).

Serving Pre-Compressed Files

During my research, I found a simple solution from a 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 a solution to detect MIME-type from the file name or extension and found the article, Getting A Mime Type From A File Name In .NET Core on the site, .NET Core Tutorials. 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 complete (for now). Those who want to use ready-made packages can use the 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 an 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 our extend static files' middleware to make it support pre-compressed files.

ASP.NET ASP.NET Core

Published at DZone with permission of Gunnar Peipman. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • GDPR Compliance With .NET: Securing Data the Right Way
  • How to Enhance the Performance of .NET Core Applications for Large Responses
  • Developing Minimal APIs Quickly With Open Source ASP.NET Core
  • Revolutionizing Content Management

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook