通过HTTP发送压缩文件(gzip)会弄乱编码



我有一个压缩文件。 如何将其发送到浏览器并使其解码?

ASP.NET 核心支持这样的压缩:

services.AddResponseCompression();
...
app.UseResponseCompresssion
app.Run(async (context) =>
{
var file = System.IO.File.ReadAllText("file.txt");
await context.Response.WriteAsync(file);
});

但是我的文件已经被压缩了。我尝试只设置标题,读取文件并发送内容,但它弄乱了编码。

app.Run(async (context) =>
{
context.Response.Headers.Add("Content-Type", "text/plain");
context.Response.Headers.Add("Content-Encoding", "gzip");
context.Response.Headers.Add("Vary", "Accept-Encoding");
var file = System.IO.File.ReadAllText("compressed.gz");
await context.Response.WriteAsync(file);
});

如果我只是发送文件,Firefox 和 chrome 会尝试下载它,但不解压缩它。

证明:

$ cat compressed.gz | hexdump | head -1
0000000 8b1f 0808 3768 5bc6 0302 6966 656c 742e
# that's the magic number: 8b 1f 08
$ curl -X GET   http://localhost:5000/  -H 'Accept-Encoding: gzip'   -H 'Cache-Control: no-cache'  --output - | hexdump | head -1
0000000 ef1f bdbf 0808 3768 bfef 5bbd 0302 6966

如何防止编码问题?

正如@t.niese指出的那样,问题在于按行阅读文本。
执行此任务的正确方法是返回FileStreamResult

例:

Response.Headers["Content-Encoding"] = "gzip";
return new FileStreamResult(new FileStream(fileName, FileMode.Open), "text/plain");

最新更新