如何在内存中构建ZipArchive并通过Web API 2中的IHttpActionResult下载?

时间:2016-06-21 15:50:38

标签: c# asp.net-web-api

我有一个Web API 2 ApiController,其中包含以下GET方法:

[HttpGet]
public IHttpActionResult GetZip()
{
    return new ZipFileActionResult();
}

我的IHttpActionResult

的自定义实现
public class ZipFileActionResult : IHttpActionResult
{
    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var memoryStream = new MemoryStream();
        var response = new HttpResponseMessage(HttpStatusCode.OK);

        using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
        {
            var entry = archive.CreateEntry("MyFileName.txt");

            using (var streamWriter = new StreamWriter(entry.Open()))
            {
                streamWriter.Write("It was the best of times, it was the worst of times...");
            }

        }

        response.Content = new StreamContent(memoryStream);
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = "example.zip"
        };
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
        return Task.FromResult(response);
    }
}

当我使用Postman进行GET时,我得到“没有回复”。创建StreamContent的断点显示流的长度约为1000字节。我错过了什么?

其他类似问题但不重复

这个问题不是重复的,虽然它似乎有一些兄弟姐妹:

1 个答案:

答案 0 :(得分:2)

您必须将object Test { def main(args: Array[String]) { val listOfFiles = List("part-00000", "part-00001", "randomFile", "part-00003", "randomFile2", "part-00004") val prefix = "part-" listOfFiles.filter(_.startsWith(prefix)).map(println) } } 位置重置为&#34; 0&#34;因此,在写入响应时,它不会尝试从文件末尾开始。固定代码应如下所示:

memoryStream