FileResult内容长度不匹配

时间:2019-03-04 15:48:37

标签: c# http .net-core content-length fileresult

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

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",
            };

1 个答案:

答案 0 :(得分:2)

您需要将流重新找回。