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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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
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

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

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

  • Teradata Performance and Skew Prevention Tips
  • Optimizing Integration Workflows With Spark Structured Streaming and Cloud Services
  • The Role of Functional Programming in Modern Software Development
  • Apache Doris vs Elasticsearch: An In-Depth Comparative Analysis
  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
10.8K 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.

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
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!