Reputation: 12002
I have a web application that is written using C# on the top of ASP.NET Core 2.2 MVC framework.
My application displays lots of images on every request which makes load time high and increase bandwidth usage. To improve page load and bandwidth usage, I want to compress the HTTP response using Brotli and Gzip formats.
Luckily Microsoft has a package that uses middleware to compress the HTTP response for me called Microsoft.AspNetCore.ResponseCompression. From the package official documentation, compression for secured websites is disabled by default.
Using compression with dynamically generated pages can lead to security problems such as the CRIME and BREACH attacks.
My question how can I compress the response while avoiding security issues?
Here is how I set up the Microsoft.AspNetCore.ResponseCompression package
public void ConfigureServices(IServiceCollection services)
{
services.AddResponseCompression(options =>
{
options.Providers.Add<BrotliCompressionProvider>();
options.Providers.Add<GzipCompressionProvider>();
options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
new[] { "image/svg+xml", "image/jpeg" });
options.EnableForHttps = true;
});
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseResponseCompression();
...
}
The above setup will apply compression for the following MIMI types
Upvotes: 2
Views: 1430
Reputation: 528
In addition, you may also "compress" image prior to sending over, for example, using :
private byte[] CompressImageToQuality(System.Drawing.Image image, int quality)
{
EncoderParameter qualityParam = new EncoderParameter(Encoder.Quality, quality);
ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");
EncoderParameters encoderParams = new EncoderParameters(1);
encoderParams.Param[0] = qualityParam;
using (var stream = new System.IO.MemoryStream())
{
image.Save(stream, jpegCodec, encoderParams);
return stream.ToArray();
}
}
Upvotes: -1