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 Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  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.

Gunnar Peipman user avatar by
Gunnar Peipman
·
Mar. 08, 19 · Tutorial
Like (2)
Save
Tweet
Share
9.94K 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, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • A Gentle Introduction to Kubernetes
  • Container Security: Don't Let Your Guard Down
  • Steel Threads Are a Technique That Will Make You a Better Engineer
  • Microservices Testing

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: