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.
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;