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.
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.
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.
Static files, such as HTML, CSS, images, and JavaScript, are assets an ASP.NET Core app serves directly to clients by default.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With