FileResult内容长度不匹配

问题描述 投票:1回答:1

您好,我正在使用此博客文章中的代码:

https://blog.stephencleary.com/2016/11/streaming-zip-on-aspnet-core.html

为了以.Net核心流式传输zip文件。我成功了,但由于当我不下载zip文件时没有在响应中添加content-length标头,因此它不会在chrome中显示下载进度。因为我事先知道zip文件的大小,所以我实际上可以使用SetHeadersAndLog方法设置content-length标头https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.internal.fileresultexecutorbase.setheadersandlog?view=aspnetcore-2.0

但是当我这样做时,出现以下错误:

System.InvalidOperationException: Response Content-Length mismatch: too many bytes written (144144633 of 144144627)

任何想法,为什么响应的长度与zip文件的长度不同?这是服务文件的代码:

     this._httpContext.Response.ContentType = "application/octet-stream";
            this._httpContext.Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
            this._httpContext.Response.ContentLength = estimatedFileSize;

            FileCallbackResult result = new FileCallbackResult(new MediaTypeHeaderValue("application/octet-stream"), estimatedFileSize, async (outputStream, _) =>
            {
                using (ZipArchive zip = new ZipArchive(outputStream, ZipArchiveMode.Create, false))
                {
                    foreach (string filepath in Directory.EnumerateFiles(existingDirectory.FullName, "*.*", SearchOption.AllDirectories))
                    {
                        string relativepath = filepath.Replace(existingDirectory.FullName + "\\", string.Empty);

                        ZipArchiveEntry zipEntry = zip.CreateEntry(relativepath, CompressionLevel.Fastest);
                        using (Stream zipstream = zipEntry.Open())
                        {
                            using (Stream stream = new FileStream(filepath, FileMode.Open))
                            {
                                await stream.CopyToAsync(zipstream);
                            }
                        }
                    }
                }
            })
            {
                FileDownloadName = $"{package.FileName}.zip",
            };
c# http .net-core content-length fileresult
1个回答
0
投票

您需要从头开始寻找流。

© www.soinside.com 2019 - 2024. All rights reserved.