簡體   English   中英

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

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

我想調用一個Web api方法,並允許用戶下載我在內存中創建的zip文件。 我也想在內存中創建條目。

我無法讓服務器正確輸出下載內容。

這是我的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;
}

這是我的調用js代碼:

window.open('api/downloadstaffdata');

這是Chrome的回復:

net::ERR_CONNECTION_RESET

我不知道我在做什么錯。 我已經搜索過SO,並閱讀了有關創建zip文件的文章,但是在嘗試將zip存檔返回給客戶端時,我無法通過連接重置錯誤。

有任何想法嗎?

您的內存流位於using塊中。 因此,將在控制器有機會將其寫出之前對您的內存流進行處置(因此, ERR_CONNECTION_RESET )。

不需要顯式地處理MemoryStream(可能需要使用其各種派生類型,但不需要MemoryStream本身)。 垃圾收集器可以自動清理它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM