diff --git a/src/FhirPseudonymizer/CompressionMiddleware.cs b/src/FhirPseudonymizer/CompressionMiddleware.cs new file mode 100644 index 0000000..10c8aff --- /dev/null +++ b/src/FhirPseudonymizer/CompressionMiddleware.cs @@ -0,0 +1,42 @@ +using System; +using System.IO.Compression; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; + +namespace FhirPseudonymizer +{ + public class RequestCompression + { + private readonly RequestDelegate next; + private const string ContentEncodingHeader = "Content-Encoding"; + private const string ContentEncodingGzip = "gzip"; + private const string ContentEncodingBrotli = "br"; + private const string ContentEncodingDeflate = "deflate"; + + public RequestCompression(RequestDelegate next) + { + this.next = next ?? throw new ArgumentNullException(nameof(next)); + } + + public async Task Invoke(HttpContext context) + { + if (context.Request.Headers.Keys.Contains(ContentEncodingHeader)) + { + switch (context.Request.Headers[ContentEncodingHeader]) + { + case ContentEncodingGzip: + context.Request.Body = new GZipStream(context.Request.Body, CompressionMode.Decompress, true); + break; + case ContentEncodingBrotli: + context.Request.Body = new BrotliStream(context.Request.Body, CompressionMode.Decompress, true); + break; + case ContentEncodingDeflate: + context.Request.Body = new DeflateStream(context.Request.Body, CompressionMode.Decompress, true); + break; + } + } + + await next(context); + } + } +} diff --git a/src/FhirPseudonymizer/Startup.cs b/src/FhirPseudonymizer/Startup.cs index 9dd40f2..8982b08 100644 --- a/src/FhirPseudonymizer/Startup.cs +++ b/src/FhirPseudonymizer/Startup.cs @@ -11,6 +11,7 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.ResponseCompression; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; @@ -38,6 +39,14 @@ public Startup(IConfiguration configuration) // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { + // services.Configure(options => options.Level = CompressionLevel.Fastest); + services.AddResponseCompression(options => + { + options.MimeTypes = + ResponseCompressionDefaults.MimeTypes.Concat( + new[] { "application/fhir+json" }); + }); + var apiKey = Configuration.GetValue("ApiKey"); services.AddAuthentication(ApiKeyDefaults.AuthenticationScheme) .AddApiKeyInHeaderOrQueryParams(options => @@ -189,6 +198,9 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env) app.UseDeveloperExceptionPage(); } + app.UseMiddleware(); + app.UseResponseCompression(); + app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v2/swagger.json", "FhirPseudonymizer v2"));