Search code examples
c#asp.net-coreasp.net-core-8

Return Stream as Response from an API


What currently I am facing is I have file saved as BsonDocument, what I am doing is converting it to memory stream and sending as response. It gives error "Cannot Access closed Stream" and if I try to use it without using statement it gives error Timeouts are not supported.

private async Task<FileStreamResult> GetImageStream(Domain.Entities.Courses.Image image)
{
    var ms = new MemoryStream(image.File!["Content"].AsByteArray);

    ms.Seek(0, SeekOrigin.Begin);
    return new FileStreamResult(ms, image.File!["ContentType"].ToString())
    {
        FileDownloadName = image.File!["FileName"].ToString()
    };

}

and also tried with using statement


Solution

  • You don't have to return a stream. It seems like you already have the file contents in your byte array. Why don't you just return a FileContentResult with your byte array?

    private IActionResult GetImage(Domain.Entities.Courses.Image image)
    {
        return FileContentResult(image.File!["Content"].AsByteArray, image.File!["ContentType"].ToString())
        {
            FileDownloadName = image.File!["FileName"].ToString()
        };
    }
    

    This way you don't have to convert your byte array into a memory stream, so it can be slightly more efficient too.

    For using with Minimal API, you can do this:

    app.MapPost("/images", (Domain.Entities.Courses.Image image) =>
    {
        return Results.File(
            fileContents: image.File!["Content"].AsByteArray, 
            contentType: image.File!["ContentType"].ToString(), 
            fileDownloadName: image.File!["FileName"].ToString()
        );
    });