未从路由 C# 接收数据

Not Receiving Data from Route C#

我正在尝试 return 来自服务器路由的图像,但我得到的图像是 0 字节。我怀疑这与我使用 MemoryStream 的方式有关。这是我的代码:

[HttpGet]
[Route("edit")]
public async Task<HttpResponseMessage> Edit(int pdfFileId)
{
    var pdf = await PdfFileModel.PdfDbOps.QueryAsync((p => p.Id == pdfFileId));

    IEnumerable<Image> pdfPagesAsImages = PdfOperations.PdfToImages(pdf.Data, 500);
    MemoryStream imageMemoryStream = new MemoryStream();
    pdfPagesAsImages.First().Save(imageMemoryStream, ImageFormat.Png);

    HttpResponseMessage response = new HttpResponseMessage();
    response.Content = new StreamContent(imageMemoryStream);
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    {
        FileName = pdf.Filename,
        DispositionType = "attachment"
    };
    return response;
}

通过调试,我已验证 PdfToImages 方法正在运行,并且 imageMemoryStream 已填充来自行

的数据
pdfPagesAsImages.First().Save(imageMemoryStream, ImageFormat.Png);

但是在 运行 中,我收到了一个正确命名但为 0 字节的附件。我需要更改什么才能接收整个文件?我认为这很简单,但我不确定是什么。提前致谢。

写入 MemoryStream 后,Flush 然后将 Position 设置为 0:

imageMemoryStream.Flush();
imageMemoryStream.Position = 0;

在将其传递给响应之前,您应该倒回 MemoryStream 到开头。但是你最好使用 PushStreamContent:

HttpResponseMessage response = new HttpResponseMessage();
response.Content = new PushStreamContent(async (stream, content, context) => 
  {
    var pdf = await PdfFileModel.PdfDbOps.QueryAsync(p => p.Id == pdfFileId);
    content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    {
      FileName = pdf.Filename,
      DispositionType = "attachment"
    };

    PdfOperations.PdfToImages(pdf.Data, 500).First().Save(stream, ImageFormat.Png);
  }, "image/png");
return response;