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.
Join the DZone community and get the full member experience.
Join For FreeOptimizing 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.
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.
Published at DZone with permission of Gunnar Peipman, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments