Search code examples
c#memorystream

C# Web.API Returning image. MemoryStream -> StreamContent returns browken image


I need to return from web service an image that is stored at the disk.

In my controller I perform some search operations and send file. Here is my code.

public HttpResponseMessage Get([FromUri]ShowImageRequest req)
{
    // .......................
    // ....................... 

    // load image file
    var imgStream = new MemoryStream();

    using (Image image = Image.FromFile(fullImagePath))
    {
        image.Save(imgStream, ImageFormat.Jpeg);
    }

    imgStream.Seek(0, SeekOrigin.Begin); // it does not work without this 

    var res = new HttpResponseMessage(HttpStatusCode.OK);
    res.Content = new StreamContent(imgStream);
    res.Content.Headers.ContentType = new ediaTypeHeaderValue("image/jpeg");
    return res;
}

If I do not add this line, I see in fiddler response body length 0

imgStream.Seek(0, SeekOrigin.Begin); 

Otherwise it works. What am I missing and why do I need to do this?


Solution

  • After saving the stream position is at the end. This means that reading from it returns no bytes.

    Everyone runs into this exact issue once :)