Method steps for pre compressing static files in ASP. NET Core

  • 2021-11-02 00:35:08
  • OfStack

Preface

Optimization of Web applications is important because using fewer CPU and using less bandwidth can reduce project costs. In ASP. NET Core, we can easily enable response compression, but for pre-compressed files, we need to do some extra functions. This blog post shows how to pre-compress static files in ASP. NET Core.

The following words are not much to say, let's take a look at the detailed introduction

Why do you need pre-compressed files?

Although we can compress files dynamically when requesting files from the server, this means that the Web server needs to do more extra work. In fact, the files to be compressed will only be changed when a new application is deployed. The better the compression effect, the more work CPU needs to do.

This fact raises the question: Is it possible to provide these files without repeatedly compressing them? Fortunately, the answer to this question is yes-yes, we can do this by extending static file middleware in ASP. NET Core.

Create a precompressed file

To keep the whole demonstration as simple as possible, we can use 7-Zip to compress static files on disk. The following is the dialog window for 7-Zip when compressing the site. css file for the default ASP. NET Core MVC application.

Here you may notice that I have enabled Ultra compression. This is obviously not the way we want to dynamically compress on the Web server, because it consumes CPU too much.

Under normal circumstances, Gulp can be used here to complete the function of bundling and shrinking files, which will not be introduced for the time being in this article.

Provide compressed files

Here I refer to a simple solution on Stack Overflow (How to gzip static content in ASP. NET Core in 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;
    }
  }
});

Of course, Javascript and CSS files are not the only file types that need to be compressed. So we can't write contentType to death here. Here I have adopted one of the solutions available in the. NET Core Tutorials site (Getting A Mime Type From A File Name In. NET Core). This plan is simple enough for me.


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

Here, I merged two solutions into one, and produced the final 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;
    }
  }
});

At this point, using the above code, the topic of this article is solved.

For those developers who want to use the off-the-shelf library directly, you can use Nuget to download the middleware made by Peter Andersson directly.

Install-Package CompressedStaticFiles -Version 1.0.4

Summarize

Although using pre-compressed files is not the mainstream of Web development, it can still save CPU and bandwidth. Compressing static files can be used as a step in building an ASP. NET Core application. Although ASP. NET Core does not support pre-compressed files out of the box, we can extend the static file middleware to support pre-compressed files.


Related articles: