Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PostingAsJsonAsync upon returning from the called method gives a 500 error

I make the following call:

var response = await Http.PostAsJsonAsync<List<CreateBookingPoLinesViewModel>>("api/downloadCsv", CreateBookingPoLinesViewModel);

and this is my method:

 [HttpPost]
 public async Task<FileStreamResult> Post([FromBody] List<CreateBookingPoLinesViewModel> value)
 {
     try
     {
         MemoryStream ms = new MemoryStream();
         var writer = new StreamWriter(ms);

         var csv = new CsvWriter(writer, CultureInfo.InvariantCulture);
        
         foreach (var line in value.Select(x => x.pOLineDTO))
         {
             csv.WriteRecord(line);
             csv.Flush();
         }
        
       
         FileStreamResult result = new FileStreamResult(ms, "text/csv")
         {
             FileDownloadName = string.Format("PoLines-{0}.csv", value.First().pOLineDTO.PurchaseOrderId)
         };
        
         return result;
     }
     catch (Exception ex)
     {

         throw;
     }
    
 }

my call to post method is also in a try/catch block and neither catch block gets hit. My post method runs to the return result line and my code has gone through the foreach and appears to write records.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

when my code returns When I look at response, it has internal server error 500.

Any body have any idea what is wrong with my post method?

>Solution :

You need to rewind your MemoryStream by setting ms.Position = 0 before returning it. I would also recommend closing the StreamWriter and CsvWriter to ensure all buffers are flushed:

var ms = new MemoryStream();

using (var writer = new StreamWriter(ms, leaveOpen : true)) // Leave the MemoryStream open after disposing of the writers
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
    foreach (var line in value.Select(x => x.pOLineDTO))
        csv.WriteRecord(line);

// Rewind the MemoryStream
ms.Position = 0;

var result = new FileStreamResult(ms, "text/csv")
{
    FileDownloadName = string.Format("PoLines-{0}.csv", value.FirstOrDefault()?.pOLineDTO?.PurchaseOrderId)
};

return result;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading