[英]How to enable compression in asp.net Core 2.2 project for https site and avoid problems like CRIME and BREACH
I have a web application that is written using C# on the top of ASP.NET Core 2.2 MVC framework.我有一个 web 应用程序,它是使用 ASP.NET Core 2.2 MVC 框架顶部的 C# 编写的。
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.为了改善页面加载和带宽使用,我想使用Brotli和Gzip格式压缩 HTTP 响应。
Luckily Microsoft has a package that uses middleware to compress the HTTP response for me called Microsoft.AspNetCore.ResponseCompression .幸运的是,微软有一个 package ,它使用中间件为我压缩 HTTP 响应,称为Microsoft.AspNetCore.ResponseCompression 。 From the package official documentation , compression for secured websites is disabled by default.从 package 官方文档中,默认情况下禁用安全网站的压缩。
Using compression with dynamically generated pages can lead to security problems such as the CRIME and BREACH attacks.对动态生成的页面使用压缩可能会导致安全问题,例如CRIME和BREACH攻击。
My question how can I compress the response while avoiding security issues?我的问题是如何在避免安全问题的同时压缩响应?
Here is how I set up the Microsoft.AspNetCore.ResponseCompression package这是我如何设置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上述设置将为以下 MIMI 类型应用压缩
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.