Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core Response Compression Middleware for static files

I've enabled response compression middleware for my asp.net core 1 application. I've noticed that after enabling this I now see the view response has content-encoding g-zip so it is working for the html.

However, I'm trying to enable it so that static files that are requested from the wwwroot of the project are sent g-zipped as well. For example a js file referenced in the head of the view or a css file. This isn't working at the moment as I see that the files are being sent without content-encoding of g-zip. Is it possible to do what I want to do, or does the middleware not kick in when requesting assets from wwwroot? Code below in configure services:

services.AddResponseCompression(options =>
{
  options.Providers.Add<GzipCompressionProvider>();
  options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(new[] { 
  "image/jpeg", "image/png", "application/font-woff2", "image/svg+xml"});
  options.EnableForHttps = true;
});

services.Configure<GzipCompressionProviderOptions>(options =>
{
  options.Level = CompressionLevel.Optimal;
});

Code in Configure:

app.UseResponseCompression();

I am also using useStaticFiles() - not sure how this might affect what I'm trying to do with compression.

like image 937
user3427689 Avatar asked Oct 19 '17 14:10

user3427689


People also ask

Does ASP.NET Core support response compression?

When you're unable to use the compression features of web servers (IIS, Apache, Nginx), ASP.NET Core provides an alternate option, Response Compression middleware.

What happens when a terminal middleware is used in the request pipeline?

These reusable classes and in-line anonymous methods are middleware, also called middleware components. Each middleware component in the request pipeline is responsible for invoking the next component in the pipeline or short-circuiting the pipeline.

What are static files in ASP.NET Core?

Static files, such as HTML, CSS, images, and JavaScript, are assets an ASP.NET Core app serves directly to clients by default.


1 Answers

The order or your middleware is very important - it determines the sequence of how each item runs. Your current code will look something like this:

app.UseStaticFiles();

//snip

app.UseResponseCompression();

Note that the static files are going to be served before the response compression middleware component runs.

So all you really need to do is ensure that the compression is added much earlier in the pipeline:

//Near the start
app.UseResponseCompression();

//snip

app.UseStaticFiles();
like image 71
DavidG Avatar answered Oct 20 '22 15:10

DavidG