Search code examples
asp.net-coreexceptionfilestreammemorystream

ASP.Net Core returns a 500 INTERNAL SERVER ERROR from a FileStreamResult


ASP.Net Core returns a 500 server error from a FileStreamResult when using MemoryStream to write into PDF

public async Task <Stream> DownloadDocumentInfoAsPdfAsync(User loggedInUser) {
    try {
        var conversionOptions = new ConversionOptions {
            Margins = new MarginSettings(20, 5.5, 10, 5.5),
        };

        //Creating new MemoryStream from byte[]
        return new MemoryStream(_htmlToPdfConverter.ConvertHtml(html, conversionOptions));
    }
}

//Returning FileStream from above function.
public async Task <IActionResult> GenerateReport([FromRoute] string info) {
    var result = await _mediator.Send(query);
    return File(result, "application/pdf", "employee.pdf"); //This will through 500 INTERNAL SERVER ERROR
}

Solution

  • If you have verified that the stream you created is valid there is a good chance that the position of the stream has not been reset to the start of the stream. The result of this is that the FileStreamResult tries to create a stream but starts from it's end position and finds no additional data and thus tries to write a blank stream out which is the cause of the error (this is not thrown as an Exception).

    The fix this problem you will want to reset the stream you're using to it's start position. The result.Position = 0; line then resets the MemoryStream before it is written out to the FileStreamResult.

    // Reset the position on the MemoryStream to the beginning in IActionResult() function before returing FileStream
    
    result.Position = 0;
    //return File(result,"application/pdf","Employee.pdf")