简体   繁体   English

从C#Web API方法下载ZipArchive在Chrome中返回“ net :: ERR_CONNECTION_RESET”

[英]Download ZipArchive from c# web api method returns “net::ERR_CONNECTION_RESET” in chrome

I want to call a web api method and have it allow the user to download a zip file that I create in memory. 我想调用一个Web api方法,并允许用户下载我在内存中创建的zip文件。 I also want to create the entries in memory as well. 我也想在内存中创建条目。

I'm having trouble getting the server to correctly output the download. 我无法让服务器正确输出下载内容。

Here is my web api method: 这是我的Web API方法:

[HttpGet]
[Route("api/downloadstaffdata")]
public HttpResponseMessage DownloadStaffData()
{
    var response = new HttpResponseMessage(HttpStatusCode.OK);
    using (var stream = new MemoryStream())
    {
        using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, true))
        {
            //future for loop to create entries in memory from staff list
            var entry = archive.CreateEntry("bob.txt");
            using (var writer = new StreamWriter(entry.Open()))
            {
                writer.WriteLine("Info for: Bob");
            }
            //future add staff images as well
        }
        stream.Seek(0, SeekOrigin.Begin);
        response.Content = new StreamContent(stream);
    }
    response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
    {
        FileName = "staff_1234_1.zip"
    };
    response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/zip");

    return response;
}

Here is my calling js code: 这是我的调用js代码:

window.open('api/downloadstaffdata');

Here is the response from Chrome: 这是Chrome的回复:

net::ERR_CONNECTION_RESET

I don't know what I'm doing wrong. 我不知道我在做什么错。 I've already searched SO and read the articles about creating the zip file, but I can't get passed the connection reset error when trying to return the zip archive to the client. 我已经搜索过SO,并阅读了有关创建zip文件的文章,但是在尝试将zip存档返回给客户端时,我无法通过连接重置错误。

Any ideas? 有任何想法吗?

You have your memory stream inside a using block. 您的内存流位于using块中。 As such, your memory stream are being disposed before your controller has the chance to write it out (hence the ERR_CONNECTION_RESET ). 因此,将在控制器有机会将其写出之前对您的内存流进行处置(因此, ERR_CONNECTION_RESET )。

A MemoryStream does not need to be disposed explicitly (its various derived type may need to be, but not the MemoryStream itself). 不需要显式地处理MemoryStream(可能需要使用其各种派生类型,但不需要MemoryStream本身)。 Garbage Collector can clean it up automatically. 垃圾收集器可以自动清理它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM