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

标签 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 获取时,我收到“无响应”。断点,其中 StreamContent创建后显示流的长度约为 1000 字节。我错过了什么?

其他类似但不重复的问题

这个问题不是重复的,尽管它似乎有一些兄弟问题:

最佳答案

您必须将 memoryStream 位置重置为“0”,以便在写入响应时不会尝试从文件末尾开始。固定代码应如下所示:

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...");
    }
}

//ADD THIS LINE
memoryStream.Position = 0;    

response.Content = new StreamContent(memoryStream);

关于c# - 如何在内存中构建ZipArchive并通过Web API 2中的IHttpActionResult下载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37949087/

相关文章:

c# - 来自命令行的自动格式代码

c# - SharpSVN 中工作目录的当前版本

c# - WinForms-何时调用Dispose?什么时候隐式?

c# - WebApi 路由导致 404(未找到)响应

c# - C#中从Json格式中提取值

c# - 这个 LINQ 查询什么时候进入数据库?

c# - 使用异步从数据库返回数据有什么好处?

asp.net-web-api - ASP.NET Core Web API : Catching Routing Errors

asp.net-web-api - Kendo Html 网格过滤器到 linq 查询

c# - PostAsJsonAsync 返回 500 内部错误