I have a static pre-compressed JS file with Brotli in ASP .NET Core 3.1. I want when a request for that file arrives ending with .js, to return the content of the pre-compressed version which is with the same name, ending with .js.br.
I tried adding some middleware code:
app.UseSpaStaticFiles(new StaticFileOptions
{
OnPrepareResponse = async (staticFilesContext) =>
{
IHeaderDictionary headers = staticFilesContext.Context.Response.Headers;
var httpContext = staticFilesContext.Context;
string contentType = headers["Content-Type"];
if (contentType == "application/javascript" && staticFilesContext.File.Name.EndsWith("somehash.chunk.js"))
{
var compressed = @$"ClientApp\build\static\js\{staticFilesContext.File.Name}";
var compressedBytes = await File.ReadAllBytesAsync(compressed);
httpContext.Response.Headers.Add("Content-Encoding", "br");
await httpContext.Response.Body.WriteAsync(compressedBytes);
}
}
});
I tried 2 npm libraries for the pre-compression:
- brotli - with that one I got decoding error in Chrome console
- brotli-max - the one I'm currently with, for which I receive the below error.
With that code, I get net::ERR_HTTP2_PROTOCOL_ERROR response in Chrome. Sometimes I get exception in Visual Studio 2019 for content length:
Response Content-Length mismatch: too many bytes written
How to properly write such a pre-compressed file as response? I'm doing pre-compression, because I'm using level 11 of Brotli which is the slowest, so dynamic compression is not an option for me.