BasicMiddleware icon indicating copy to clipboard operation
BasicMiddleware copied to clipboard

Response Compression allows re-compressing of already compressed responses

Open speige opened this issue 8 years ago • 4 comments

I serve pre-compressed static files via a custom middleware (discussed here https://github.com/aspnet/Home/issues/1584)

If I add app.UseResponseCompression(); in Startup.cs Configure method the response will be compressed 2x.

This can obviously be avoided by re-ordering the middleware, but it seems like ResponseCompressionProvider should double-check the Response headers to see if the Content-Encoding value indicates that it's already compresed.

speige avatar Feb 17 '18 11:02 speige

i coded up a possible solution. let me know if you'd like a pull request.

	public class CustomResponseCompressionProvider : ResponseCompressionProvider
	{
		public CustomResponseCompressionProvider(IServiceProvider services, IOptions<ResponseCompressionOptions> options) : base(services, options)
		{
		}

		public override bool ShouldCompressResponse(HttpContext context)
		{
			if (!string.IsNullOrWhiteSpace(context.Response.Headers["Content-Encoding"]) && !string.Equals(context.Response.Headers["Content-Encoding"], "identity", StringComparison.InvariantCultureIgnoreCase))
			{
				return false;
			}

			return base.ShouldCompressResponse(context);
		}
	}

It can be used in the ConfigureServices method of Startup.cs like this:

			services.Configure<GzipCompressionProviderOptions>(options => options.Level = System.IO.Compression.CompressionLevel.Fastest);
			services.Configure((ResponseCompressionOptions options) =>
			{
				options.Providers.Add<BrotliCompressionProvider>();
				options.Providers.Add<GzipCompressionProvider>();
				options.EnableForHttps = true;
				options.MimeTypes = new[]
				{
					// Default
					"text/plain",
					"text/css",
					"application/javascript",
					"text/html",
					"application/xml",
					"text/xml",
					"application/json",
					"text/json",

					// Custom
					"application/atom+xml",
					"application/xaml+xml",
					"application/svg+xml",
					"image/svg+xml",
					"application/vnd.ms-fontobject",
					"font/otf"
				};
			});
			services.TryAddSingleton<IResponseCompressionProvider, CustomResponseCompressionProvider>();

The normal UseResponseCompression(); in Startup.cs Configure should still work.

speige avatar Feb 17 '18 11:02 speige

I have same issue i.e response is double compressed (in my case this happens when I use proxy). Is it possible his fix will be added to ResponseCompressionProvider?

melnikov77 avatar Sep 14 '18 23:09 melnikov77

Adding a StringValues.IsNullOrEmpty check for Content-Encoding would be reasonable. Are you interested in sending a PR to the release/2.2 branch?

Tratcher avatar Sep 14 '18 23:09 Tratcher

Sure, will do it

melnikov77 avatar Sep 19 '18 20:09 melnikov77