Do not receive data from C # route

I am trying to return an image from a server route, but I am getting one that is 0 bytes. I suspect this has something to do with how I use MemoryStream . Here is my code:

 [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; } 

Through debugging, I checked that the PdfToImages method works and that imageMemoryStream populated with data from a string

 pdfPagesAsImages.First().Save(imageMemoryStream, ImageFormat.Png); 

However, when I start, I get an attachment that is correctly named, but is 0 bytes. What do I need to change to get the whole file? I think it's simple, but I'm not sure what. Thanks in advance.

+5
source share
2 answers

After writing to MemoryStream , Flush then set Position to 0:

 imageMemoryStream.Flush(); imageMemoryStream.Position = 0; 
+2
source

You must rewind MemoryStream to the beginning before passing it back. But it is better to use 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
source

Source: https://habr.com/ru/post/1232813/


All Articles