C# 未从路由C接收数据#

C# 未从路由C接收数据#,c#,.net,routes,attachment,memorystream,C#,.net,Routes,Attachment,Memorystream,我试图从服务器路由返回一个映像,但得到的是一个0字节的映像。我怀疑这与我如何使用MemoryStream有关。这是我的密码: [HttpGet] [Route("edit")] public async Task<HttpResponseMessage> Edit(int pdfFileId) { var pdf = await PdfFileModel.PdfDbOps.QueryAsync((p => p.Id == pdfFileId)); IEnume

我试图从服务器路由返回一个映像,但得到的是一个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;
}

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

在写入
内存流后,
刷新
然后将
位置设置为0:

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

您应该将
MemoryStream
倒带到start,然后再将其传递给response。但您最好使用
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;

也许您必须将流位置设置为0<代码>imageMemoryStream.Position=0
使用
PushStreamContent
的保证是什么?无需为
MemoryStream
分配额外内存。在测试代码时,它是通过内联方式,而不是作为附件。关于原因有什么想法吗?它似乎也挂起了,在标签头上有一个旋转的轮子。至于内容配置-通过http捕获检查发送了哪些标题。关于“挂起”-如果不进行调试,就无法确定。
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;